1. 排序
Stream<T> sorted(); //按元素默认大小排序(必须实现Comparable接口)
Stream<T> sorted(Comparator<? super T> cp); //按指定Comparator比较的结果排序
public static void main(String[] args){
Stream<String> s = Stream.of("hello","JAVA","python","RUBY","PHP");
s.sorted().forEach(str-> System.out.print(str+" "));
System.out.println();
Stream<Integer> s1 = Stream.of(1,9,5,3,7);
s1.sorted(Comparator.reverseOrder()).forEach(str-> System.out.print(str+" "));
}
## 2.去除重复元素
Stream3. 截取
Stream<T> limit(long); //截取Stream前long个元素
Stream<T> skip(long); //跳过Stream前long个元素
Stream<String> s = Stream.of("hello","JAVA","hello","RUBY","JAVA");
s.limit(3).forEach(str-> System.out.print(str+" "));
System.out.println();
Stream<Integer> s1 = Stream.of(1,9,5,3,7);
s1.skip(3).forEach(str-> System.out.print(str+" "));
4. concat合并
Stream<String> s1 = Stream.of("php","JAVA","python");
Stream<String> s2 = Stream.of("android", "ios");
Stream<String> s = Stream.concat(s1,s2);
s.forEach(str-> System.out.print(str+" "));
## 5. flatMap把列表的元素取出,构成一个新的Stream
把元素映射为Stream,然后合并成一个新的Stream
List<String> s1 = new ArrayList<>();
s1.add( "php");
s1.add("JAVA");
s1.add("python");
List<String> s2 = Arrays.asList("android", "ios");
Stream<List> l = Stream.of(s1,s2);
Stream<String> s = l.flatMap(list -> list.stream());
s.forEach(str-> System.out.print(str+" "));
6. parallel把一个Stream转换为可以并行处理的Stream
Stream的元素是串行处理的,也就是只能用单线程来处理,如果要提高效率,比如进行并行排序,只需使用parallel()就可以把一个Stream变成一个并行处理的Stream,通过这个方法调用,后续的操作会尽量的并行处理。
Stream<String> s = Stream.of("php","JAVA","python","android", "ios");
String[] result = s.parallel() //变成一个可以并行处理的Stream
.sorted(). //可以进行并行排序
toArray(String[]::new);
System.out.println(Arrays.toString(result));
## 7. Stream的聚合方法
Optional