【Java/排序】将对象列表排序的三种常用方式
对象列表排序是日常操作之一,常见方式有三种(Comparable接口、lamda表达式、Comparator),各有其长,现整理列出以备查。
代码:
package com.hy.lab.sortSamples; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Test { public static void main(String[] args){ // 1.Emp实现Comparable接口,用Collections.sort进行排序 List<Emp> ls1=new ArrayList<>(); ls1.add(new Emp("Douglas",50)); ls1.add(new Emp("Andy",20)); ls1.add(new Emp("Bill",30)); ls1.add(new Emp("Cindy",40)); Collections.sort(ls1); for(Emp e:ls1){ System.out.println(e); } System.out.println("---------------------------------------------------"); // 2.用lamda表达式进行排序,不触动Emp2 List<Emp2> ls2=new ArrayList<>(); ls2.add(new Emp2("Cindy",40)); ls2.add(new Emp2("Douglas",50)); ls2.add(new Emp2("Andy",20)); ls2.add(new Emp2("Bill",30)); ls2.sort((Emp2 a,Emp2 b)->a.getName().compareTo(b.getName()));// 一行流 for(Emp2 e:ls2){ System.out.println(e); } System.out.println("---------------------------------------------------"); // 3.用Comparator进行排序,不触动Emp3 List<Emp3> ls3=new ArrayList<>(); ls3.add(new Emp3("Bill",30)); ls3.add(new Emp3("Cindy",40)); ls3.add(new Emp3("Douglas",50)); ls3.add(new Emp3("Andy",20)); ls3.sort(new Comparator<Emp3>() { @Override public int compare(Emp3 a, Emp3 b) { return a.getName().compareTo(b.getName()); } }); for(Emp3 e:ls3){ System.out.println(e); } } }
输出:
Emp name=Andy age=20 Emp name=Bill age=30 Emp name=Cindy age=40 Emp name=Douglas age=50 --------------------------------------------------- Emp2 name=Andy age=20 Emp2 name=Bill age=30 Emp2 name=Cindy age=40 Emp2 name=Douglas age=50 --------------------------------------------------- Emp3 name=Andy age=20 Emp3 name=Bill age=30 Emp3 name=Cindy age=40 Emp3 name=Douglas age=50
下面是三个对象类。
Emp类:
package com.hy.lab.sortSamples; public class Emp implements Comparable<Emp>{ private String name; private int age; public Emp(String name,int age){ this.name=name; this.age=age; } public String toString(){ return String.format("Emp name=%s age=%d",name,age); } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int compareTo(Emp o) { return this.name.compareTo(o.name); } }
Emp2类:
package com.hy.lab.sortSamples; public class Emp2 { private String name; private int age; public Emp2(String name, int age){ this.name=name; this.age=age; } public String toString(){ return String.format("Emp2 name=%s age=%d",name,age); } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Emp3类:
package com.hy.lab.sortSamples; public class Emp3 { private String name; private int age; public Emp3(String name, int age){ this.name=name; this.age=age; } public String toString(){ return String.format("Emp3 name=%s age=%d",name,age); } public String getName() { return name; } public void setName(String name) { this.name = name; } }
END