Steam流排序去重
1、工作中我们经常会遇到排序去重问题,传统做法就是拿到数组遍历然后去重,现在我们可以使用Stream流来快速帮我们解决去重排序问题;
class Student{
private Integer id;
private String UserName;
private Integer age;
//get set省略
//equals hashcode 省略 对象去重的时候需要
public class StreamDemo {
public static void main(String[] args) {
Student student1 = new Student(11,"a1",22);
Student student2 = new Student(11,"a2",23);
Student student3 = new Student(12,"a2",24);
Student student5 = new Student(16,"a5",26);
Student student4 = new Student(14,"a4",24);
List<Student> students = Arrays.asList(student2, student1, student3, student4,student5);
//对象去重
students.stream().distinct().collect(Collectors.toList()).forEach(System.out::println);
System.out.println("--------------------");
//属性去重
students.stream().filter(distinctByKey(Student::getUserName)).forEach(System.out::println);
System.out.println("--------------------");
//根据属性排序
students.stream().sorted(Comparator.comparing(Student::getAge)).forEach(System.out::println);
students.stream().filter(t->{
return t.getId()%2 == 0;
}).filter(u->{return u.getAge() > 22; }).map(m->{return m.getUserName().toUpperCase();}).sorted(Comparator.reverseOrder()).forEach(System.out::println);
}
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
}
返回结果如下图:
如有不足之处,请多指教。