ArrayList list = new ArrayList<>(){{add(1);add(9);add(2);add(4);add(3);}};// 比较方法Comparator<Integer> normal = Integer::compareTo;// 过滤添加Predicate<Integer> predicate = x -> x.intValue() < 4;System.out.println(list.stream().sorted(normal).collect(Collectors.toList()).toString());System.out.println(list.stream().sorted(normal).filter(predicate).collect(Collectors.toList()).toString());List<Integer> res = (List<Integer>) list.stream().sorted(normal).collect(Collectors.toList());// 独立的方式方法Collections.sort(res,normal.reversed());System.out.println(res);System.out.println(Optional.ofNullable(res).toString());List list1 = null;// 保证空对象也不报错System.out.println(Optional.ofNullable(list1).toString());// 这里会报错System.out.println(list1.toString());
结果为:
stream中的对象去重
public static void main(String[] args) {List<Person> list = new ArrayList<Person>(){{add(Person.builder().id(1L).name("哈哈哈").sex("男").build());add(Person.builder().id(2L).name("哈哈哈2").sex("女").build());add(Person.builder().id(3L).name("哈哈哈").sex("男").build());}};//赋值初始化过程省略List<Person> uniqueByName = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new));System.out.println(uniqueByName);}@Data@SuperBuilder(toBuilder = true)public static class Person {private Long id;private String name;private String sex;}
结果为:
