TreeMap集合自定义对象的遍历排序方式


第一部分:

package day11;
//创建学生类
public class Student{
//成员变量
private String name;
private int age;
//构造方法
public Student(){
super();
}

public Student(String name, int age){
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 +
'}';
}
}

第二部分:
package day11;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeMap;

public class TreDemo2 {
public static void main(String[] args){
      //创建treemap集合对象,并用比较器排序
TreeMap<Student, String> map = new TreeMap<>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num = s2.getAge()-s1.getAge();
int num2 = num==0?s1.getName().compareTo(s2.getName()):num;
return num2;
}
});
        //添加元素
Student s1 = new Student("张无忌",50);
Student s2 = new Student("赵敏",45);
Student s3 = new Student("金毛狮王",60);
Student s4 = new Student("周芷若",40);
        //把元素添加到集合中去
map.put(s1,"红楼梦");
map.put(s2,"西游记");
map.put(s3,"水浒传");
map.put(s4,"捉妖记");

//获取键的集合
Set<Student> k = map.keySet();
//遍历
for (Student key: k){
//根据键找值
String value = map.get(key);
System.out.println(key.getName()+key.getAge()+"---"+value);
}
}
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM