本文主要分享运用 Java8 中的 Lambda.stream.sorted方法排序的使用!
sorted()
:默认自然排序;
@Test
public void testSorted1() {
List<Integer> list = Lists.newArrayList(2,5,3,4,1,2,6,7,9,1);
List<Integer> collect = list.stream().sorted().collect(Collectors.toList());
System.out.println(JSONObject.toJSONString(collect));
}
运行结果:
倒序需要结合 Comparator.reverseOrder()
方法使用:
@Test
public void testSorted1() {
List<Integer> list = Lists.newArrayList(2,5,3,4,1,2,6,7,9,1);
List<Integer> collect = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
System.out.println(JSONObject.toJSONString(collect));
}
sorted(Comparator super T> comparator)
:通过创建 Comparator
实例,按照指定规则升/降序排序元素。
按生日升序:
@Test
public void testSorted2() {
List<Student> list = this.getStudent();
List<Student> collect = list.stream().sorted(Comparator.comparing(Student::getBirthday))
.collect(Collectors.toList());
System.out.println(JSONObject.toJSONString(collect));
}
按生日降序:
@Test
public void testSorted2() {
List<Student> list = this.getStudent();
List<Student> collect = list.stream().sorted(Comparator.comparing(Student::getBirthday, Comparator.reverseOrder()))
.collect(Collectors.toList());
System.out.println(JSONObject.toJSONString(collect));
}
排序说明:
生日升序;
学号降序;
@Test
public void testSorted2() {
List<Student> list = this.getStudent();
List<Student> collect = list.stream().sorted(Comparator.comparing(Student::getBirthday)
.thenComparing(Student::getNum, Comparator.reverseOrder()))
.collect(Collectors.toList());
System.out.println(JSONObject.toJSONString(collect));
}
student对象:
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Student {
/**
* 姓名
*/
private String name;
/**
* 年龄
*/
private Integer age;
/**
* 生日
*/
@JSONField(format="yyyy-MM-dd HH:mm:ss")
private Date birthday;
/**
* 学号
*/
private Integer num;
}
mock数据:
public List<Student> getStudent() {
return Lists.newArrayList(
new Student("小张", 17, DateUtil.parse("2006-10-03 15:18:56"), 11),
new Student("小李", 15, DateUtil.parse("2008-03-19 02:18:56"), 5),
new Student("小李", 15, DateUtil.parse("2008-03-19 02:18:56"), 2),
new Student("小王", 16, DateUtil.parse("2007-02-21 22:18:56"), 29));
}
eUtil.parse("2008-03-19 02:18:56"), 2),
new Student("小王", 16, DateUtil.parse("2007-02-21 22:18:56"), 29));
}