How to interleave (merge) two Java 8 Streams?

前端 未结 6 1852
有刺的猬
有刺的猬 2020-12-16 16:43
 Stream a = Stream.of(\"one\", \"three\", \"five\");
 Stream b = Stream.of(\"two\", \"four\", \"six\");

What do I need

6条回答
  •  一向
    一向 (楼主)
    2020-12-16 17:29

    This may not be a good answer because
    (1) it collects to map, which you don't want to do I guess and
    (2) it is not completely stateless as it uses AtomicIntegers.

    Still adding it because
    (1) it is readable and
    (2) community can get an idea from this and try to improve it.

    Stream a = Stream.of("one", "three", "five");
    Stream b = Stream.of("two", "four", "six");
    
    AtomicInteger i = new AtomicInteger(0);
    AtomicInteger j = new AtomicInteger(1);
    
    Stream.of(a.collect(Collectors.toMap(o -> i.addAndGet(2), Function.identity())),
            b.collect(Collectors.toMap(o -> j.addAndGet(2), Function.identity())))
            .flatMap(m -> m.entrySet().stream())
            .sorted(Comparator.comparing(Map.Entry::getKey))
            .forEach(e -> System.out.println(e.getValue())); // or collect
    

    Output

    one
    two
    three
    four
    five
    six
    

    @Holger's edit

    Stream.concat(a.map(o -> new AbstractMap.SimpleEntry<>(i.addAndGet(2), o)),
            b.map(o -> new AbstractMap.SimpleEntry<>(j.addAndGet(2), o)))
            .sorted(Map.Entry.comparingByKey())
            .forEach(e -> System.out.println(e.getValue())); // or collect
    

提交回复
热议问题