peek(Consumer c) 获取流中元素,操作流中元素,与foreach不同的是不会截断流,可继续操作流
//篮球俱乐部所有成员名 + 赞助商商标^_^,并且获取所有队员详细内容 List<Student> collect = basketballClub.stream() .peek(e -> e.setName(e.getName() + "^_^")) .collect(Collectors.toList()); collect.forEach(System.out::println); //Student{idNum='2015134012',, age=13, classNum='1503'} //Student{idNum='2015134013',, age=14, classNum='1503'} //Student{idNum='2015134015',, age=15, classNum='1504'} //Student{idNum='2015134018',, age=16, classNum='1505'}
distinct() 通过流所生成元素的equals和hashCode去重
limit(long val) 截断流,取流中前val个元素
sorted(Comparator) 产生一个新流,按照比较器规则排序
sorted() 产生一个新流,按照自然顺序排序
List<String> list = Arrays.asList("b","b","c","a"); list.forEach(System.out::print); //bbca List<String> collect = list.stream().distinct().sorted().collect(Collectors.toList()); collect.forEach(System.out::print);//abc //获取list中排序后的top2 即截断取前两个 List<String> collect1 = list.stream().distinct().sorted().limit(2).collect(Collectors.toList()); collect1.forEach(System.out::print);//ab 匹配booelan allMatch(Predicate) 都符合
.boolean anyMatch(Predicate) 任一元素符合
boolean noneMatch(Predicate) 都不符合
boolean b = basketballClub.stream().allMatch(e -> e.getAge() < 20); boolean b1 = basketballClub.stream().anyMatch(e -> e.getAge() < 20); boolean b2 = basketballClub.stream().noneMatch(e -> e.getAge() < 20); 寻找元素findFirst——返回第一个元素
findAny——返回当前流中的任意元素
Optional<Student> first = basketballClub.stream().findFirst(); if (first.isPresent()) { Student student = first.get(); System.out.println(student); } Optional<Student> any = basketballClub.stream().findAny(); if (any.isPresent()) { Student student2 = any.get(); System.out.println(student2); } Optional<Student> any1 = basketballClub.stream().parallel().findAny(); System.out.println(any1); 计数和极值count——返回流中元素的总个数
max——返回流中最大值
min——返回流中最小值
long count = basketballClub.stream().count(); Optional<Student> max = basketballClub.stream().max(Comparator.comparing(Student::getAge)); if (max.isPresent()) { Student student = max.get(); } Optional<Student> min = basketballClub.stream().min(Comparator.comparingInt(Student::getAge)); if (min.isPresent()) { Student student = min.get(); }