Java中Set转List 和 TreeMap中实现自定义类作为key值

时间:2021-09-09 16:09:52


Map转Set & Set转List


        //构造Map数据
Map<String, String> map = new HashMap<String, String>();
map.put("ele1", "小樱");
map.put("ele2", "若曦");
map.put("ele3", "晴川");
Set<String> set = map.keySet();

//Set转List,方法一 : ArrayList(Collection<?> c)
List<String> list1 = new ArrayList<String>(set);
for(int i = 0; i < list1.size(); i++){
System.out.println("list1(" + i + ") --> " + list1.get(i));
}

//Set转List,方法二:List实现类(ArrayList/LinkedList)的方法 -- addAll(Collection<?> c)
List<String> list2 = new ArrayList<String> ();
list2.addAll(set);
for(String elem : list2){
System.out.println(elem);
}



在TreeMap中,如果key值是java中的基本类型,TreeMap会自身帮我们排序,如果是自定义类型,如定义一个Student类作为key值,我们如果不告知排序规则的话,运行就会报错。所以,如何实现自定义排序呢?解决方案有2个,二者选一即可:

  • 在Student类中实现Comparable,重写compareTo方法
  • 在构造函数中new Comparator,匿名内部类,重写compare 方法

代码如下:

public class Student implements Comparable<Student>{
private String name;
private int age;

public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}

@Override
public int compareTo(Student o) {
int num1 = this.getAge()-o.getAge();
int num2 = num1==0?this.getName().compareTo(o.getName()):num1;
return num2;
}


public class TestTreeMap {
public static void main(String[] args) {
//1.创建集合
TreeMap<Student, String> map = new TreeMap<Student, String>(new Comparator<Student>() {
//按照年龄来排序,年龄相同按照姓名来排序
@Override
public int compare(Student o1, Student o2) {
if(o1.getAge()==o2.getAge()){
return o1.getName().compareTo(o2.getName());
}
return o1.getAge()-o2.getAge();
}
//2.创建学生对象并往集合中增加
Student s1 = new Student("张三",27);
Student s2 = new Student("李四",29);
Student s3 = new Student("王五",16);
Student s4 = new Student("张三",27);
map.put(s1, "2001");
map.put(s2, "2002");
map.put(s3, "2003");
map.put(s4, "2004");

//3.遍历集合 ,排序完成
Set<Student> set = map.keySet();
for(Student student : set){
String value = map.get(student);
System.out.println(student.getName()+"=="+student.getAge()+"=="+value);
}
}
}