我们把Stream提供的操作分为两类:转换操作和聚合操作。除了前面介绍的常用操作外,Stream还提供了一系列非常有用的方法。
/**
* @Auther Mario
* @Version 1.0
* @description
*/
public class Main {
public static void main(String[] args) {
//排序
List<String> list = List.of("Orange", "apple", "Banana");
List<String> collect = list.
stream().
sorted(String::compareToIgnoreCase).
// sorted().
collect(Collectors.toList());
System.out.println(collect);
//去重
List.of("A", "B", "A", "C", "B", "D").
stream().
distinct().
collect(Collectors.toList());
//截取
List.of("A", "B", "C", "D", "E", "F").stream().skip(2).limit(3).collect(Collectors.toList());
//合并
Stream<String> s1 = List.of("A", "B", "C").stream();
Stream<String> s2 = List.of("e", "f", "d").stream();
Stream<String> s3 = Stream.concat(s1,s2);
//flatMap
Stream<List<Integer>> s = Stream.of(
Arrays.asList(1,2,3),
Arrays.asList(3,4,5),
Arrays.asList(4,5,6)
);
Stream<Integer> stream = s.flatMap(list1 -> list1.stream());
//并行
Stream<String> stringStream = Stream.of("A", "B", "C", "D", "E", "F");
String[] collect1 = stringStream.parallel().sorted().toArray(String[]::new);
System.out.println(collect1);
}
}
所谓flatMap(),是指把Stream的每个元素(这里是List)映射为Stream,然后合并成一个新的Stream: