Zipping streams using JDK8 with lambda (java.util.stream.Streams.zip)

前端 未结 14 1627
旧巷少年郎
旧巷少年郎 2020-11-21 23:24

In JDK 8 with lambda b93 there was a class java.util.stream.Streams.zip in b93 which could be used to zip streams (this is illustrated in the tutorial Exploring Java8 Lambda

14条回答
  •  庸人自扰
    2020-11-21 23:33

    This is great. I had to zip two streams into a Map with one stream being the key and other being the value

    Stream streamA = Stream.of("A", "B", "C");
    Stream streamB  = Stream.of("Apple", "Banana", "Carrot", "Doughnut");    
    final Stream> s = StreamUtils.zip(streamA,
                        streamB,
                        (a, b) -> {
                            final Map.Entry entry = new AbstractMap.SimpleEntry(a, b);
                            return entry;
                        });
    
    System.out.println(s.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())));
    

    Output: {A=Apple, B=Banana, C=Carrot}

提交回复
热议问题