Stream流

2020-04-02  本文已影响0人  GIT提交不上

一、创建流

二、常用方法

//forEach() - 终止操作
List<String> testList = Arrays.asList("hello","world","luffy","luffy","just");
testList.stream().forEach(System.out::println);
//count() - 终止操作
long num = testList.stream().count();
System.out.println(num);
//limit(n)-截断流 
testList.stream().limit(5).forEach(System.out::println);
//skip(n)-跳过元素
testList.stream().skip(1).forEach(System.out::println);
//distinct()-筛选,通过流所生成元素的hashCode()和equals()去除重复元素 
testList.stream().distinct().forEach(System.out::println);
//map()-映射,改变元素
testList.stream().map(e->Arrays.asList(e).stream()).forEach(System.out::println);
//flatMap()-映射,解决流中流
 testList.stream().flatMap(e->Arrays.asList(e).stream()).forEach(System.out::println);
//sorted()-自然排序
testList.stream().distinct().sorted().forEach(System.out::println);
//sorted(Comparator comparator)-定制排序
testList.stream().distinct().sorted((e1,e2)->{return e1.substring(2,3).compareTo(e2.substring(2,3));}).forEach(System.out::println);
//allMatch()-检查是否匹配所有元素
boolean flag1 =  testList.stream().distinct().allMatch(e->e.length()>5);
System.out.println(flag1);
//anyMatch()-检查是否至少匹配一个元素
boolean flag2 =  testList.stream().distinct().anyMatch(e->e.length()>5);
System.out.println(flag2);
//noneMatch()-检查是否没有匹配所有元素
boolean flag3 =  testList.stream().distinct().noneMatch(e->e.length()>5);
System.out.println(flag3);
//findFirst()-返回第一个元素
Optional<String> optional1 =  testList.stream().distinct().findFirst();
System.out.println(optional1.get());
//findAny()-返回当前流中的任意元素
Optional<String> optional2 =  testList.stream().distinct().findAny();
System.out.println(optional2.get());
//max(Comparator comparator)-返回流中最大值
Optional<String> optional3 =  testList.stream().distinct().max((e1,e2)->{return e1.substring(2,3).compareTo(e2.substring(2,3));});
System.out.println(optional3.get());
//min(Comparator comparator)-返回流中最小值 
Optional<String> optional4 = testList.stream().distinct().min((e1,e2)->{return e1.substring(2,3).compareTo(e2.substring(2,3));});
System.out.println(optional4.get());
//reduce()-归约操作
Optional<String> optional5 =  testList.stream().distinct().reduce(String::concat);
System.out.println(optional5.get());
//collect(Collectors)-将流转换为其他形式,接收一个Collector接口实现 ,用于给Stream中汇总的方法
System.out.println(testList.stream().distinct().collect(Collectors.maxBy((e1, e2) -> {
    return e1.substring(2, 3).compareTo(e2.substring(2, 3));
})));
//流复用
Supplier<Stream<List<String>>> streamSupplier = () -> Stream.of(testList);
streamSupplier.get().distinct().count();
streamSupplier.get().distinct().count();
//关闭流-try-with-resources(jdk1.7)
try (Stream<String> stream = testList.stream()){

}catch (Exception e){

}
//map-reduce模式
//并行流-Fork/Join-工作窃取(parallelStream())
Integer[] integers = new Integer[]{12,23,23,23,232,2323};
System.out.println(Arrays.stream(integers).parallel().map(e -> Math.pow(e, 2)).reduce(Double::sum));
上一篇下一篇

猜你喜欢

热点阅读