一、stream常用方法
-
forEach
List<String> one = new ArrayList<>(); Collections.addAll(one, "迪丽热巴", "宋远桥", "苏星河", "老子", "庄子", "孙子"); one.stream().forEach(System.out::println);
-
count
System.out.println(one.stream().count());
-
filter
one.stream().filter(s -> s.length() == 2).forEach(System.out::println);
-
limit
one.stream().limit(3).forEach(System.out::println);
-
skip
one.stream().skip(2).forEach(System.out::println);
-
map
Stream<String> original = Stream.of("11", "22", "33"); Stream<Integer> result = original.map(Integer::parseInt); result.forEach(s -> System.out.println(s + 10));
-
sorted
Stream.of(33, 22, 11, 55) .sorted() .sorted((o1, o2) -> o2 - o1) .forEach(System.out::println);
-
distinct
Stream.of(22, 33, 22, 11, 33) .distinct() .forEach(System.out::println); //自定义对象distinct,自定义类型是根据对象的hashCode和equals来去除重复元素的。 Stream.of( new Person("刘德华", 58), new Person("张学友", 56), new Person("张学友", 56), new Person("黎明", 52) ).distinct().forEach(System.out::println);
-
match
boolean b = Stream.of(5, 3, 6, 1) // .allMatch(e -> e > 0); // allMatch: 元素是否全部满足条件 // .anyMatch(e -> e > 5); // anyMatch: 元素是否任意有一个满足条件 .noneMatch(e -> e < 0); // noneMatch: 元素是否全部不满足条件 System.out.println("b = " + b);
-
find
Optional<Integer> first = Stream.of(5, 3, 6, 1).findFirst(); System.out.println("first = " + first.get()); Optional<Integer> any = Stream.of(5, 3, 6, 1).findAny(); System.out.println("any = " + any.get());
-
max/min
Optional<Integer> max = Stream.of(5, 3, 6, 1).max((o1, o2) -> o1 - o2); System.out.println("first = " + max.get()); Optional<Integer> min = Stream.of(5, 3, 6, 1).min((o1, o2) -> o1 - o2); System.out.println("any = " + min.get());
-
reduce
int reduce = Stream.of(4, 5, 3, 9).reduce(0, (a, b) -> { System.out.println("a = " + a + ", b = " + b); return a + b; }); int reduce2 = Stream.of(4, 5, 3, 9).reduce(0, (x, y) -> { return Integer.sum(x, y); }); int reduce3 = Stream.of(4, 5, 3, 9).reduce(0, Integer::sum); int max = Stream.of(4, 5, 3, 9).reduce(0, (x, y) -> { return x > y ? x : y; });
-
map+reduce
// 求出所有年龄的总和 int totalAge = Stream.of( new Person("刘德华", 58), new Person("张学友", 56), new Person("郭富城", 54), new Person("黎明", 52) ).map((p) -> p.getAge()).reduce(0, (x, y) -> x + y); System.out.println("totalAge = " + totalAge); // 找出最大年龄 int maxAge = Stream.of( new Person("刘德华", 58), new Person("张学友", 56), new Person("郭富城", 54), new Person("黎明", 52) ).map((p) -> p.getAge()).reduce(0, (x, y) -> x > y ? x : y); System.out.println("maxAge = " + maxAge); // 统计 数字2 出现的次数 int count = Stream.of(1, 2, 2, 1, 3, 2).map(i -> { if (i == 2) { return 1; } else { return 0; } }).reduce(0, Integer::sum); System.out.println("count = " + count);
-
mapToInt
-
concat
Stream<String> streamA = Stream.of("张三"); Stream<String> streamB = Stream.of("李四"); Stream<String> result = Stream.concat(streamA, streamB); result.forEach(System.out::println);
-
Stream综合案例
List<String> one = List.of("迪丽热巴", "宋远桥", "苏星河", "老子", "庄子", "孙子", "洪七公"); List<String> two = List.of("古力娜扎", "张无忌", "张三丰", "赵丽颖", "张二狗", "张天爱","张三"); // 第一个队伍只要名字为3个字的成员姓名; // 第一个队伍筛选之后只要前3个人; Stream<String> streamOne = one.stream().filter(s -> s.length() == 3).limit(3); // 第二个队伍只要姓张的成员姓名; // 第二个队伍筛选之后不要前2个人; Stream<String> streamTwo = two.stream().filter(s -> s.startsWith("张")).skip(2); // 将两个队伍合并为一个队伍; // 根据姓名创建Person对象; // 打印整个队伍的Person对象信息。 Stream.concat(streamOne, streamTwo).map(Person::new).forEach(System.out::println);
-
收集Stream流中的结果
//1. 收集结果到集合中 Stream<String> stream = Stream.of("aa", "bb", "cc"); // List<String> list = stream.collect(Collectors.toList()); // Set<String> set = stream.collect(Collectors.toSet()); ArrayList<String> arrayList = stream.collect(Collectors.toCollection(ArrayList::new)); HashSet<String> hashSet = stream.collect(Collectors.toCollection(HashSet::new)); //2. 收集结果到数组中 Stream<String> stream = Stream.of("aa", "bb", "cc"); // Object[] objects = stream.toArray(); // for (Object obj : objects) { // System.out.println(); // } String[] strings = stream.toArray(String[]::new); for (String str : strings) { System.out.println(str); } //3. 对流中数据进行聚合计算 Stream<Student> studentStream = Stream.of( new Student("赵丽颖", 58, 95), new Student("杨颖", 56, 88), new Student("迪丽热巴", 56, 99), new Student("柳岩", 52, 77)); // 获取最大值 // Optional<Student> collect = studentStream.collect(Collectors.maxBy((o1, o2) ->o1.getSocre() - o2.getSocre())); // 获取最小值 // Optional<Student> collect = studentStream.collect(Collectors.minBy((o1, o2) ->o1.getSocre() - o2.getSocre())); // System.out.println(collect.get()); // 求总和 // int sumAge = studentStream.collect(Collectors.summingInt(s -> s.getAge())); // System.out.println("sumAge = " + sumAge); // 平均值 // double avgScore = studentStream.collect(Collectors.averagingInt(s -> s.getSocre())); // System.out.println("avgScore = " + avgScore); // 统计数量 // Long count = studentStream.collect(Collectors.counting()); // System.out.println("count = " + count); //4. 对流中数据进行分组 // 分组 @Test public void testGroup() { Stream<Student> studentStream = Stream.of( new Student("赵丽颖", 52, 95), new Student("杨颖", 56, 88), new Student("迪丽热巴", 56, 55), new Student("柳岩", 52, 33)); // Map<Integer, List<Student>> map = studentStream.collect(Collectors.groupingBy(Student::getAge)); // 将分数大于60的分为一组,小于60分成另一组 Map<String, List<Student>> map = studentStream.collect(Collectors.groupingBy((s) -> { if (s.getSocre() > 60) { return "及格"; } else { return "不及格"; } })); map.forEach((k, v) -> { System.out.println(k + "::" + v); }); } //5. 对流中数据进行多级分组 @Test public void testCustomGroup() { Stream<Student> studentStream = Stream.of( new Student("赵丽颖", 52, 95), new Student("杨颖", 56, 88), new Student("迪丽热巴", 56, 99), new Student("柳岩", 52, 77)); Map<Integer, Map<String, List<Student>>> map = studentStream.collect(Collectors.groupingBy(s -> s.getAge(), Collectors.groupingBy(s -> { if (s.getSocre() >= 90) { return "优秀"; } else if (s.getSocre() >= 80 && s.getSocre() < 90) { return "良好"; } else if (s.getSocre() >= 80 && s.getSocre() < 80) { return "及格"; } else { return "不及格"; } }))); map.forEach((k, v) -> { System.out.println(k + " == " + v); }); } //6. 对流中的数据进行分区 @Test public void testPartition() { Stream<Student> studentStream = Stream.of( new Student("赵丽颖", 52, 95), new Student("杨颖", 56, 88), new Student("迪丽热巴", 56, 99), new Student("柳岩", 52, 77)); // partitioningBy会根据值是否为true,把集合分割为两个列表,一个true列表,一个false列表。 Map<Boolean, List<Student>> map = studentStream.collect(Collectors.partitioningBy(s -> s.getSocre() > 90)); map.forEach((k, v) -> { System.out.println(k + " == " + v); }); } //7. 对流中数据进行拼接 @Test public void testJoining() { Stream<Student> studentStream = Stream.of( new Student("赵丽颖", 52, 95), new Student("杨颖", 56, 88), new Student("迪丽热巴", 56, 99), new Student("柳岩", 52, 77)); String collect = studentStream .map(Student::getName) .collect(Collectors.joining(">_<", "^_^", "^v^")); System.out.println(collect); }