java1.8特性之多重排序简单示例
Posted superdrew
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java1.8特性之多重排序简单示例相关的知识,希望对你有一定的参考价值。
1. 实体类:Student.java
package java8newfeture; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import com.google.common.collect.Lists; /** * @author zero 2019/01/26 */ public class Student { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Student() { } /** * @param id * @param name */ public Student(int id, String name) { super(); this.id = id; this.name = name; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + "]"; } }
2. 测试类:SortStudent.java
package java8newfeture; import java.util.ArrayList; import java.util.Comparator; import com.google.common.collect.Lists; /** * @author zero 2019/01/26 */ public class SortStudent { public static void main(String[] args) { ArrayList<Student> students = Lists.newArrayList(new Student(1, "A2"),new Student(1, "A1"), new Student(3, "C3"), new Student(2, "B2")); // 默认是升序排序,降序为comparing(Student::getId).reversed().thComparing(Student::getName)
// 如果是需要按照某个字段降序排序,则在后面调用方法reversed() students.sort(Comparator.comparing(Student::getId).thenComparing(Student::getName)); students.forEach(System.out::println); } }
3. 测试结果:
4. 结论:亲测有效,请自己扩展尝试!
以上是关于java1.8特性之多重排序简单示例的主要内容,如果未能解决你的问题,请参考以下文章