Java中将自定义对象存入到集合中,集合根类Collections自带排序方法
我们先来写一段代码,目的按从小到大的顺序输出实例化对象的成绩
public class Demo01 {
//测试类
//
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Student> list = new ArrayList<>();
list.add(new Student("李四",18));
list.add(new Student("万一",21));
list.add(new Student("一万",13));
list.add(new Student("王五",18));
list.add(new Student("赵六",28));
list.add(new Student("张三",11));
//Collections.sort(list);
for (Student student : list) {
System.out.println(student.getAge());
}
}
}
//====================================
//自定义对象类
public class Student {
private String name ;
private int 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;
}
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
}
运行结果为
很明显这并没有达到我想要的效果
很明显,Java中不允许直接对自定义的对象调用sort直接排序,需要实现Comparable接口。按照上面的方法改造一下Student.java
方法一:让Student对象实现Comparable接口,并在测试类中调用方法Collections.sort();
public class Student implements Comparable<Student>{
private String name ;
private int 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;
}
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub
return getAge() - o.getAge();
}
}
运行结果达到了我想要的效果
方法二:Student对象不作任何改动,添加一个比较器AgeComparator.java,执行Collections.sort(list,new AgeComparator());
public class AgeComparator implements Comparator<Student> {
//新建类继承Comparator类,重写比较方法
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return (o1.getAge()>o2.getAge()?-1:(o1.getAge()<o2.getAge()?1:0));
}
}
运行结果也能达到效果
顺便说一下Comparable和Comparator的区别:
1. Comparable和Comparator都是用来实现集合中元素的比较、排序的,只是Comparable是在集合内部定义的方法实现的排序,Comparator是在集合外部实现的排序,所以想要实现排序,就需要在集合外定义Comparator接口或在集合内实现Comparable接口两种方法。
- Comparable实现的排序只能是自然排序,这里的自然顺序就是实现Comparable接口设定的排序方式(Demo是按照年龄从小到大排序)。而Comparator是一个专用的比较器,当这个对象不支持自比较或者自比较函数不能满足你的要求时,你可以写一个比较器来完成两个对象之间大小的比较。
如何将Map按照value值大小排序?
public class Test03 {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<String, Integer> map = new HashMap<>();
map.put("张三", 23);
map.put("李四", 22);
map.put("王五", 26);
map.put("赵六", 12);
map.put("皮七", 20);
}
}
我们先来分析一波map
Map是键值对的集合接口,它的实现类主要包括:HashMap,TreeMap,Hashtable以及LinkedHashMap等。
TreeMap:基于红黑树(Red-Black tree)的 NavigableMap 实现,该映射根据其键的自然顺序进行排序,或者根据创建映射时提供的 Comparator 进行排序,具体取决于使用的构造方法。
HashMap的值是没有顺序的,它是按照key的HashCode来实现的,对于这个无序的HashMap我们要怎么来实现排序呢?参照TreeMap的value排序。
Map.Entry返回Collections视图。~其实就是反映它的键值对应关系
将map转换为list就可以实现对它的排序
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap