Java 8中的排序算法功能极其强大,无论在写法上还是可读性上都完全超越前代sort。总的来说Java 8中的sort()有两种,第一种替代了老版的sort,用lambda语句优化;第二种用在stream中,可以参照我后面的文章。如果你还在创建Comparator去排序,一定要看看我这篇blog。
首先我们来比较一下比较简单的sort。
对于Array的sort:
对于List.sort(), 可以用lambda表达式自定义sort
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
initIntArray(list);
list.sort((i1,i2)->i2-i1);
System.out.println(list);
}
private static void initIntArray(List l) {
for (int i = 0; i < 10; i++) {
l.add((int)(100 * Math.random() / 1));
}
}
输出结果为:
[83, 68, 61, 53, 33, 29, 28, 21, 15, 11]
下面来说一下类的sort
如果类只有单一条件的比较,直接用上文所提到的lambda表达式排序即可。但若有多重的条件,比如先按name排序,name相同的话按age排序。可用Comparator中的thenComparing方法定义次要排序条件。reverse方法可以调整顺序或者倒序。代码如下:
public class Sort {
public static class Overwatch {
String name;
int age;
public Overwatch(String name, int age) {
// TODO Auto-generated constructor stub
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() {
// TODO Auto-generated method stub
return name+":"+age;
}
}
public static void main(String[] args) {
List<Overwatch> l = new ArrayList<>();
initList(l);
// l.sort((Overwatch o1, Overwatch o2)->(o1.name.compareTo(o2.name)));
l.sort(Comparator.comparing(Overwatch::getName).reversed().
thenComparingInt(Overwatch::getAge).reversed());
// l.sort(Comparator.comparing(Overwatch::getName).reversed().
// thenComparingInt(Overwatch::getAge));
// l.sort(Comparator.comparing(Overwatch::getName).
// thenComparingInt(Overwatch::getAge));
// l.sort(Comparator.comparing(Overwatch::getName).
// thenComparingInt(Overwatch::getAge).reversed());
System.out.println(l);
}
private static void initList(List<Overwatch> list) {
// TODO Auto-generated method stub
list.add(new Overwatch("Tracer",23));
list.add(new Overwatch("Tracer",19));
list.add(new Overwatch("Tracer",24));
list.add(new Overwatch("Genji",39));
list.add(new Overwatch("Reinhardt",61));
list.add(new Overwatch("Reinhardt",45));
list.add(new Overwatch("Mercy",37));
list.add(new Overwatch("Mercy",27));
list.add(new Overwatch("Mccree",39));
list.add(new Overwatch("Ana",49));
list.add(new Overwatch("Dva",26));
}
}
四种排序结果分别如下(注意reverse的位置):
name: 小->大; age: 大->小
[Ana:49, Dva:26, Genji:39, Mccree:39, Mercy:37, Mercy:27, Reinhardt:61, Reinhardt:45, Tracer:24, Tracer:23, Tracer:19]
name: 大->小; age: 小->大
[Tracer:19, Tracer:23, Tracer:24, Reinhardt:45, Reinhardt:61, Mercy:27, Mercy:37, Mccree:39, Genji:39, Dva:26, Ana:49]
name: 小->大; age: 小->大
[Ana:49, Dva:26, Genji:39, Mccree:39, Mercy:27, Mercy:37, Reinhardt:45, Reinhardt:61, Tracer:19, Tracer:23, Tracer:24]
name: 大->小; age: 大->小
[Tracer:24, Tracer:23, Tracer:19, Reinhardt:61, Reinhardt:45, Mercy:37, Mercy:27, Mccree:39, Genji:39, Dva:26, Ana:49]