创建无限流
- 迭代
Stream<Integer> iterate = Stream.iterate(0, x -> x + 2);
iterate.forEach(System.out::println);
//iterate.limit(10).forEach(System.out::println);
会从0开始+2的方式一直输出数据,如果只想要前10个,就加上limit。
- 生成
Stream.generate(() -> Math.random()).forEach(System.out::println);
无限生成随机数。
筛选和切片(中间操作)
多个中间操作可以连接起来形成一个流水线,除非流水线触发终止操作,否则中间操作不会执行任何处理,而在终止操作时一次性全部处理,称为“惰性求值”。
distinct()
的去重是依赖equals()
和hashCode()
List<UserTest> list = new ArrayList<>();
list.add(new UserTest(1, "李四"));
list.add(new UserTest(1, "李四"));
list.add(new UserTest(2, "王五"));
list.add(new UserTest(2, "王五"));
list.add(new UserTest(3, "赵六"));
list.stream().distinct().forEach(System.out::println);
在没有重写 UserTest
的 equals
和hashCode
UserTest{id=1, name='李四'} UserTest{id=1, name='李四'} UserTest{id=2, name='王五'} UserTest{id=2, name='王五'} UserTest{id=3, name='赵六'}重写`UserTest` 的 `equals` 和`hashCode` ``` @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof UserTest)) return false; UserTest userTest = (UserTest) o; if (id != userTest.id) return false; return name != null ? name.equals(userTest.name) : userTest.name == null; } @Override public int hashCode() { int result = id; result = 31 * result + (name != null ? name.hashCode() : 0); return result; } ``` >UserTest{id=1, name='李四'} UserTest{id=2, name='王五'} UserTest{id=3, name='赵六'}
-
filter
接收Lambda,从流中排除某些元素 -
limit
截断流,使其元素不超过指定个数 -
skip
跳过元素,返回一个扔掉了前n个元素的流, 若流中元素不够n个则返回一个空流,与limit互补。
映射(中间操作)
map
接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射到成一个新的元素。
List<String> list = Arrays.asList("aaa", "nnn", "vvv");
Stream<Stream<Character>> streamStream = list.stream().map(OperateTest::filterCharacter);
streamStream.forEach((sm) -> sm.forEach(System.out::println));
flatMap
接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有的流连接成一个流。
Stream<Character> characterStream = list.stream().flatMap(OperateTest::filterCharacter);
characterStream.forEach(System.out::println);
根据 map
和 flatMap
的返回值可以知道, map
返回的是嵌套流,flatMap
是返回一个流,打印之后的结果是一样的,map
返回的嵌套流会在后面的输出时,多次变量,而 flatMap
就很好的解决了这个问题。
排序(中间操作)
-
sorted() 自然排序
-
sorted(Comparator com) 定制排序
list.stream().sorted(Comparator.comparing(UserTest::getId).thenComparing(UserTest::getName)).forEach(System.out::println);
查找与匹配(终止操作)
allMatch
检查是否匹配所有元素
boolean result = list.stream().allMatch(e -> e.getName().equals("李四"));
System.out.println(result); // false
anyMatch
检查是否至少匹配一个元素
boolean result = list.stream().anyMatch(e -> e.getName().equals("李四"));
System.out.println(result); // true
noneMath
是否没有匹配所有元素
boolean reuslt = list.stream().noneMatch(e -> e.getName().equals("田七"));
System.out.println(reuslt); // true
findFirst
返回第一个元素
Optional<UserTest> first = list.stream().sorted(Comparator.comparing(UserTest::getId)).findFirst();
System.out.println(first.get());
按照id排序之后,返回第一个元素。
findAny
返回当前流中的任意元素
Optional<UserTest> result = list.parallelStream().filter(e -> e.getName().equals("李四")).findAny();
System.out.println(result.get());
-
count
返回元素的个数 -
max
返回最大值
Optional<UserTest> max = list.stream().max(Comparator.comparing(UserTest::getId));
System.out.println(max);
min
返回最小值
Optional<Integer> min = list.stream().map(UserTest::getId).min(Integer::compareTo);
System.out.println(min);
归约(终止操作)
reduce(T identity, BinaryOperator) / reduce(BinaryOperator)
可以将流中元素反复结合起来,返回一个值
Integer reduce = list.stream().map(UserTest::getId).reduce(0, (x, y) -> x + y);
System.out.println(reduce);
Optional<Integer> reduce = list.stream().map(UserTest::getId).reduce(Integer::sum);
System.out.println(reduce.get());
使用 map
和 reduce
List<UserTest> list = new ArrayList<>();
list.add(new UserTest(1, "李四"));
list.add(new UserTest(1, "李四"));
list.add(new UserTest(2, "王五"));
list.add(new UserTest(2, "王五"));
list.add(new UserTest(3, "赵六"));
Optional<Integer> reduce = list.stream().map(UserTest::getId).reduce(Integer::sum);
System.out.println(reduce.get());
收集(终止操作)
collect(Collector c) 将流转换成其他形式,接收一个Collector接口的实现,用于给Stream中元素做汇总的方法
-
toList() 返回list集合
-
toSet() 返回set集合
-
toCollection(HashSet::new)
-
counting() 获取总数
-
averagingInt(ToIntFunction mapper) 获取平均值
Double collect = list.stream().collect(Collectors.averagingInt(UserTest::getId));
- summingInt(ToIntFunction mapper) 获取总和
Integer collect = list.stream().collect(Collectors.summingInt(UserTest::getId));
- maxBy 最大值(不建议使用,建议直接使用上面的max())
Optional<UserTest> collect = list.stream().collect(Collectors.maxBy(Comparator.comparing(UserTest::getId)));
- groupingBy 分组
Map<Integer, List<UserTest>> collect = list.stream().collect(Collectors.groupingBy(UserTest::getId));
- partitioningBy 分区
Map<Boolean, List<UserTest>> collect = list.stream().collect(Collectors.partitioningBy(e -> e.getId() > 3));
System.out.println(collect);
输出
{false=[UserTest{id=1, name='李四'}, UserTest{id=2, name='王五'}, UserTest{id=1, name='李四'}, UserTest{id=3, name='赵六'}], true=[UserTest{id=5, name='王五'}]}