Java8的Stream流真香,没体验过的永远不会知道
1. 取出以张开头,并且长度等于的三的数据,并打印
stream.fiter()
ArrayList<String> list = new ArrayList<>(); Collections.addAll(list,"张三","李四","王五","张三丰","张无忌"); list.stream().filter(s -> s.startsWith("张") ) .filter(s -> s.length()==3).forEach(System.out::println );
2.升序 ,降序 ,去重
升序: stream.sorted()
降序: stream.sorted(( i1, i2)-> i2-i1)
去重: stream.distinct()
ArrayList<Integer> list2 = new ArrayList<Integer>(); Collections.addAll(list2, 1, 4, 56, 8, 9, 2, 4, 8, 76); //升序 list2.stream().sorted().forEach(System.out::println); //降序 list2.stream().sorted(( i1, i2)-> i2-i1).forEach(System.out::println);//去重 list2.stream().distinct().sorted().forEach(System.out::println);
3. 取最大最小值
最大值: stream.max((o1, o2) ->o1 - o2)
最小值: stream.min((o1, o2) ->o2 - o1)
最大值: stream().reduce(0, (x, y) -> x > y ? x : y
Optional<Integer> max = list2.stream().max((o1, o2) -> o1 - o2); System.out.println(max.get()); Optional<Integer> min = list2.stream().min((o1, o2) -> o2 - o1); System.out.println(min.get()); Integer max = list2.stream().reduce(0, (x, y) -> x > y ? x : y); System.out.println(max);
4. 对年龄求和
stream().map(student -> student.age).reduce(0, Integer::sum)
将student的age属性映射进集合,然后用Integer中的sum方法求和
ArrayList<Student> students = new ArrayList<>(); Collections.addAll(students, new Student("张三", 23), new Student("李四", 24), new Student("王五", 25)); Integer sumAge = students.stream().map(student -> student.age).reduce(0, Integer::sum); System.out.println(sumAge);
5.求年龄的最大值
stream().map(student -> student.age).reduce(0, Integer::max)
stream().map(student -> student.age).reduce(0, Math::max)
将student的age属性映射进集合,然后用Integer中的max方法求最大值,或者用math中的max求最大值.
ArrayList<Student> students = new ArrayList<>(); Collections.addAll(students, new Student("张三", 23), new Student("李四", 24), new Student("王五", 25)); Integer maxAge = students.stream().map(student -> student.age).reduce(0, Integer::max); Integer maxAge2 = students.stream().map(student -> student.age).reduce(0, Math::max); System.out.println(maxAge); System.out.println(maxAge2);
6.将两个流合并
stream.concat(stream1,stream2),合并后,stream1和 stream2流不可用
ArrayList<Integer> list2 = new ArrayList<Integer>(); Collections.addAll(list2, 1, 4, 56, 8, 9, 2, 4, 8, 76); ArrayList<Integer> list3 = new ArrayList<Integer>(); Collections.addAll(list3, 5, 56,48,1001); list2.stream().mapToInt(Integer::intValue).filter(n->n>3).forEach(System.out::println); Stream<Integer> streamConcat = Stream.concat(list2.stream(), list3.stream()); streamConcat.forEach(System.out::println); list2.forEach(System.out::println);
7. 小案例
// 1.只要第一个队中名字大于三个字的成员姓名 // 2.第一个队伍筛选后,只要前两人 // 3.第二个队伍只要名字带有乔的 // 4.第二个队伍筛选不要第一个人 // 5.将两个队伍合成一个队伍 // 6.根据姓名创建Student对象 // 7.打印队伍的Student信息
List<String> team1=new ArrayList<>(); Collections.addAll(team1,"赵云","韩信","鲁班七号","狄仁杰","公孙离","杨玉环"); List<String> team2=new ArrayList<>(); Collections.addAll(team2,"李白","李信","黄忠","二乔","大乔","小乔"); Stream<String> stream1 = team1.stream().filter(s -> s.length() >= 3).limit(2); Stream<String> stream2 = team2.stream().filter(s -> s.contains("乔")).skip(1); Stream<String> streamConcat = Stream.concat(stream1, stream2); streamConcat.map(Student2::new).forEach(System.out::println);
8. 将流中结果保存进集合
`将流中数据放入list集合中
stream.collect(Collectors.toList());
将流中数据放入ArrayList集合stream.collect(Collectors.toCollection(ArrayList::new));
将流中数据放入HashSet集合stream.collect(Collectors.toCollection(HashSet::new));
ArrayList list = new ArrayList(); Collections.addAll(list,23,32,2,8,5,1);
将结果装入list集合
List list2 = list.stream().filter(s -> s > 5).collect(Collectors.toList());
System.out.println(list2);
ArrayList list3 = list.stream().filter(s -> s > 5).collect(Collectors.toCollection(ArrayList::new)); System.out.println(list3);
将结果存入set集合
HashSet list4 = list.stream().filter(s -> s > 5).collect(Collectors.toCollection(HashSet::new)); System.out.println(list4);`
9. 对流中数据进行聚合函数操作
求最大值:
stream().collect(Collectors.maxBy((s1, s2) -> s1.getScore() - s2.getScore())
求最大值:
stream().collect(Collectors.maxBy((s1, s2) -> s1.getScore() - s2.getScore())
求总和:
stream().collect(Collectors.summingInt(s -> s.getAge()))
求平均值:
stream().collect(Collectors.averagingInt(Student::getScore));
统计个数:
stream().collect(Collectors.counting())
`ArrayList students = new ArrayList<>(); Collections.addAll(students, new Student(“张三”, 23, 97), new Student(“李四”, 24, 56), new Student(“王五”, 25, 89));
//获取最大值 Optional maxScore = students.stream().collect(Collectors.maxBy((s1, s2) -> s1.getScore() - s2.getScore())); System.out.println(maxScore.get());
//获取最小值 Optional minScore = students.stream().min((s1, s2) -> s1.getScore() - s2.getScore());
System.out.println(minScore.get());
//求总和 Integer sumAge = students.stream().collect(Collectors.summingInt(s -> s.getAge())); Integer sumAge1 = students.stream().mapToInt(Student::getAge).sum(); System.out.println(sumAge);
//求平均值 Double avgScore = students. System.out.println(avgScore); Long count = students.stream().collect(Collectors.counting()); Long count2 = students.stream().count(); System.out.println(count);`
10. 分组
根据年龄分组分组: stream().collect(Collectors.groupingBy(Student::getAge))
根据分数是否及格分组: stream().collect(Collectors.groupingBy(s->s.getScore>60));
先根据年龄分组,再根据成绩分组:
stream().collect(Collectors.groupingBy(Student::getAge, Collectors.groupingBy(s ->s.getScore>60)));
map遍历:
map.forEach((k,v)->{System.out.println(k+":"+v);})
//根据年龄分组分组
`Map<Integer, List> groupAgeMap = students.stream().collect(Collectors.groupingBy(Student::getAge)); groupAgeMap.forEach((k,v)->{ System.out.println(k+":"+v); });
//根据分数是否及格分组
Map<String, List> groupAgeMap = students.stream().collect(Collectors.groupingBy(s-> { if (s.getScore() >=60) { return “及格”; }else { return “不及格”; } }));
groupAgeMap.forEach((k,v)->{ System.out.println(k+":"+v); });
//先根据年龄分组,再根据成绩分组
Map<Integer, Map<String, List>> groupMap = students.stream().collect(Collectors.groupingBy(Student::getAge, Collectors.groupingBy(s -> { if (s.getScore() >= 60) { return “及格”; } else { return “不及格”; } }))); //遍历 groupMap.forEach((k,v)->{ System.out.println(k); v.forEach((k2,v2)->{ System.out.println("\t"+k2+"=="+v2); }); });`
11.收集流中的结果进行拼接
根据一个字符串拼接
stream.map(Student::getName).collect(Collectors.joining(“±=”));
根据三个字符串拼接
stream().map(Student::getName).collect(Collectors.joining("@", “start”, “end”));
`ArrayList students = new ArrayList<>(); Collections.addAll(students, new Student(“张三”, 25, 97), new Student(“李四”, 24, 56), new Student(“王五”, 25, 89),new Student(“赵六”, 24, 89));
//收集流中的结果进行拼接
//根据一个字符串拼接
String oneString= students.stream().map(Student::getName).collect(Collectors.joining(“±=”)); System.out.println(oneString);
//根据三个字符串拼接 String threeString = students.stream().map(Student::getName).collect(Collectors.joining("@", “start”, “end”)); System.out.println(threeString);`
12. 串行,并行流. parallelStream会存在线程安全问题
方式一: 直接获取并行stream
list2.parallelStream()
方式二: 将串行流转换成并行stream
list2.stream().parallel()
ArrayList list2 = new ArrayList(); Collections.addAll(list2, 1, 4, 56, 8, 9, 2, 4, 8, 76);
`//串行stream流 list2.stream().filter(s -> { System.out.println(Thread.currentThread() + “::” + s); return s > 3; }).count();
//并行stream流 list2.stream().parallel().filter(s -> { System.out.println(Thread.currentThread() + “::” + s); return s > 3; }).count();
//并行stream流
//方式一: 直接获取并行stream Stream parallelStream1 = list2.parallelStream();
//方式二: 将串行流转换成并行stream Stream parallelStream2 = list2.stream().parallel();`
13. Optional空值校验
ifPresent :如果有值就调用函数
// Optional userName=Optional.empty(); Optional userName=Optional.of(“张三”); //存在做什么 //ifPresent :如果有值就调用函数 userName.ifPresent(s->{ System.out.println(“有值”); });
ifPresentOrElse(有值做什么,无值做什么) JDK9才有
userName.ifPresentOrElse(s->{ System.out.println(“有值”); },()-> { System.out.println(“无值”); });
对double求平均出现空值报错,OptionalDouble的isPresent()进行叫校验
double activeDiscoveryScoreDay = 0d; OptionalDouble average = resultList.stream().mapToDouble(DepartmentControlMark::getActiveDiscoveryScore).average(); if (average.isPresent()) { activeDiscoveryScoreDay = average.getAsDouble(); } return activeDiscoveryScoreDay;