写一个Stream流中collectionandthen的使用例子
时间: 2023-05-24 17:01:50 浏览: 68
当使用流(Stream)处理集合(Collection)时,使用collectionandthen可以将多个集合合并为一个流,比如:
List<String> list1 = Arrays.asList("apple", "banana", "pear");
List<String> list2 = Arrays.asList("orange", "grape", "kiwi");
List<String> list3 = Arrays.asList("watermelon", "pineapple", "melon");
list1.stream()
.flatMap(s -> Stream.of(s.toUpperCase(), s.toLowerCase()))
.collect(Collectors.toList())
.stream()
.peek(System.out::println)
.collect(Collectors.toSet());
这个例子中,我们首先创建了三个字符串类型的集合,然后通过list1的流将每个字符串分别转换成大写和小写两个字符串,使用collect收集起来为一个列表,然后再转换成流。
使用collectionandthen可以将list1, list2, list3三个集合合并为一个流:
Stream.of(list1, list2, list3)
.flatMap(Collection::stream)
.forEach(System.out::println);
这里我们使用Stream.of将三个集合作为一个可变参数传入,然后通过flatMap将每个集合中的元素转换成流,最后通过forEach打印每个元素。
希望本例子能对你有所帮助。