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<String> stream1 = Stream.empty();//空序列流
Stream<String> stream2 = Stream.of("1");//单序列流
Stream<String> stream3 = Stream.of("1", "2", "3");//序列流

                3.2  数组创建流:

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

                 3.3 集合创建流

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

                 3.4 Stream接口静态方法

//<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)  f为输入t,返回t
Stream.iterate(1,x->x+1).limit(4).forEach(x-> System.out.println(x));//1换行2换行3换行4换行
//<T> Stream<T> generate(Supplier<T> 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<String> 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<Apple> 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<? super T, ? extends Stream<? extends R>> 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<? super T> 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<T> max/min(Comparator<? super T> comparator)  注意返回值是Optional<T>  取流中最大值和最小值
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<? super T, ? extends IntStream> 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<T> reduce(BinaryOperator<T> 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<T, A, R> {
        // A容器  T为元素  R返回结果 

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


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

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

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

//apples对象按颜色分类,颜色相同按重量分类,返回值 Map<String, Map<Integer, List<Apple>>>
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 陆明刚 劳佳 译

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值