栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java JDK8新特性Stream流

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java JDK8新特性Stream流

1.Stream流

        1. 流,支持处理数据处理操作的源生成的元素序列。流有两个重要特性:1流水线:很多流操作本身会返回一个流,这样多的操作就可以链接起来,形成一个大的流水线。2,内部迭代。流的迭代是在背后进行的。流可以看成遍历数据集的高级迭代器。此外,流还可以透明的并行处理,你无需写任何多线程代码。

        2.在package java.util.stream包下,有一个父类接口 baseStream,抽取的子类许多共有的方法,常用的如关闭流close()、判读终端操作前是否执行并行操作isParallel()等等。子类接口:IntStream,Stream,DoubleStream。我们重点介绍Stream接口:

          3.生成流的方法:

                3.1  静态方法Stream.of():

Stream stream1 = Stream.empty();//空序列流
Stream stream2 = Stream.of("1");//单序列流
Stream stream3 = Stream.of("1", "2", "3");//序列流

                3.2  数组创建流:

//Stream Arrays.stream(T[])   
//Stream Arrays.stream(T[] array, int startInclusive, int endExclusive)
Stream stream = Arrays.stream(new String[]{"11", "22"});

                 3.3 集合创建流

//List Set  
Stream stream1 = Collections.emptyList().stream(); 

                 3.4 Stream接口静态方法

// Stream iterate(final T seed, final UnaryOperator f)  f为输入t,返回t
Stream.iterate(1,x->x+1).limit(4).forEach(x-> System.out.println(x));//1换行2换行3换行4换行
// Stream generate(Supplier s)  一般 t为随机数 如Math.random()
Stream.generate(()->4).limit(4).forEach(x-> System.out.println(x));//4换行4换行4换行4换行
Stream.builder().add("2").add("3").build()//23

                 3.5 文件中获取流

//test.txt内容
//  aa dd
//  cc bb           
//Stream lines(Path path)
Files.lines(Paths.get("C:\Users\14145\Desktop\test.txt")).forEach(x-> System.out.println(x));//aa dd换行cc bb

        4.流的中间操作:skip、filter、map、flatmap、reduce等方法

ArrayList apples = new ArrayList<>();
apples.add(new Apple(5,"红色"));
apples.add(new Apple(4,"绿色"));
apples.add(new Apple(20,"绿色"));
apples.add(new Apple(11,"绿色"));
apples.stream()
     //掉过前面2个对象
     .skip(2)
     //过滤到weight小于等于4的对象
     .filter(a->a.getWeight()>4)
     //对象转为String
     .map(a->a.getColor())
     //打印输出对象
     .forEach(x-> System.out.println(x));

//flatMap(Function> mapper) mapper参数输入t,输出流对象r  distinct() 去重  count() 计数
Stream.of("s,g","g,r").flatMap(var->Arrays.stream(var.split(","))).distinct().count()//count()前: s换行g换行r换行 count()后:3

//流转成数组
Stream.of("s,g", "g,r").toArray(String[]::new);//["s,g","g,r"]

//boolean allMatch(Predicate predicate) 流中的每一个元素符合条件,返回true
System.out.println(Stream.of("s,g", "g,r").allMatch(var -> var.contains("g")));//true
//流中的元素至少有一个满足条件,返回true
System.out.println(Stream.of("s,g", "g,r").anyMatch(var->var.contains("s")));//true
//流中的元素任意一个都不满足条件,返回true
System.out.println(Stream.of("s,g", "g,r").noneMatch(var -> var.contains("f")));//true

//Optional max/min(Comparator comparator)  注意返回值是Optional  取流中最大值和最小值
System.out.println(Stream.iterate(1, x -> x+1).limit(4).max(Integer::compareTo).get());//4
System.out.println(Stream.iterate(1, x -> x + 1).limit(4).min(Integer::compareTo).get());//1

//固定返回1
System.out.println(Stream.iterate(1, x -> x + 1).limit(4).findAny().get());
//并行流,随机返回
System.out.println(Stream.iterate(1, x -> x + 1).limit(4).parallel().findAny().get());
//返回第一个元素
System.out.println(Stream.iterate(1, x -> x + 1).limit(4).findFirst().get());

//IntStream flatMapToInt(Function mapper) mapper 传入t,返回IntStream流
Stream.of("1,3","2,4").flatMapToInt(x->Stream.of(x.split(",")).mapToInt(v->Integer.parseInt(v))).forEach(x-> System.out.println(x));//1换行3换行2换行4


//Optional reduce(BinaryOperator accumulator) 累计器
System.out.println(Stream.of(1,2,3,4,5).reduce((x, y) ->
{
    System.out.println("x:"+x+","+"y:"+y);
    return x+y;
}).get());//x作用累加变量,y作用传值
//累计器,给定初始值
System.out.println(Stream.of(1,2,3,4,5).reduce(1,(x,y)->{
    System.out.println("x:"+x+","+"y:"+y);
    return x+y;
}));//x作用累加变量,y作用传值
//reduce() 三参数
System.out.println(Stream.of("8", "2","3","9","14").reduce("1", (x,y)->{
    System.out.println(x+"&"+y);
    return x+y;
},(x,y)->{
     System.out.println(x+","+y);
     return x+y;
  }));//1823914 注意:通过多次调用研究结果第三个参数没起作用
//parallel()流结果改变
System.out.println(Stream.of("8", "3","2","9","14").parallel().reduce("1", (x,y)->{
      System.out.println(x+"&"+y);//调4次,顺序可能不一样
            return x+y;
  },(x,y)->{
      System.out.println(x+","+y);//调4-1次,顺序不一样
      return x+y;
     }));//18131219114 注意:可能会不同电脑调用结果可能不同


//bug调试
Stream.of("1","3")
       .peek(x-> System.out.println("Stream后:"+x))
       .map(x->x+"1")
       .peek(x-> System.out.println("map后:"+x))
       .collect(Collectors.toList());
2.Collectors 收集器

                2.1 Collector接口:

public interface Collector {
        // A容器  T为元素  R返回结果 

        //提供容器
        Supplier supplier();
        //将T添加到容器
        BiConsumer accumulator();
        //容器之间操作
        BinaryOperator combiner();
        //容器处理后,返回结果
        Function finisher();
}


//apples对象按颜色分类,返回值 Map
apples.stream().collect(Collectors.groupingBy(Apple::getColor));

//apples对象按颜色分类后统计计数,返回值 Map
apples.stream().collect(Collectors.groupingBy(Apple::getColor, Collectors.counting()));

//apples对象的重量按颜色分类后,返回值 Map>
apples.stream().collect(Collectors.groupingBy(Apple::getColor, Collectors.mapping(Apple::getColor, Collectors.toList())));

//apples对象按颜色分类,颜色相同按重量分类,返回值 Map>
apples.stream().collect(Collectors.groupingBy(Apple::getColor, Collectors.groupingBy(Apple::getWeight)));

System.out.println(Stream.of("1", "2", "3").collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString());//123
System.out.println(Stream.of("1", "2", "3").collect(
Collectors.joining("&", "begin&", "&end")));//begin&1&2&3&end
System.out.println(Stream.of(1, 2, 3).collect(Collectors.averagingInt(var -> var)));//2.0


//第一个参数生成key 第二个参数生成value 第三个参数解决key冲突(传b,覆盖值,传a,保持原有key值)
System.out.println(apples.stream().collect(Collectors.toMap(Apple::getColor, Function.identity(),(q,b)->{
            System.out.println(q+","+b);
            return b;
        })));

[1]: Java8 实战 java 8 in Action Mario Fusco 著 Alan Mycroft 陆明刚 劳佳 译

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号