Create stream of streams from one long stream

前端 未结 4 1916
一向
一向 2020-12-10 15:31

I want to split a single Stream into a Stream of Streams based on the contents of the Streams. The resulting the St

4条回答
  •  温柔的废话
    2020-12-10 16:10

    Like @Jaroslaw, I also used Map to hold the different Streams. However, it is doable that the map will hold Streams that are built from the input and are not collected upfront. Using Stream.concat and Stream.of you can add one element to a stream:

        Map> streamMap = new HashMap<>();
    
        int[] arr = {1,1,1,2,2,2,3,6,7,7,1,1};
        Arrays.stream(arr)
        .filter(this::isOdd)
        .forEach(i -> {
            Stream st = streamMap.get(i);
            if (st == null)  st = Stream.of(i);
            else st = Stream.concat(st, Stream.of(i));
            streamMap.put(i, st);
        });
    
        streamMap.entrySet().stream().forEach(e -> {
            System.out.print(e.getKey() + "={");
            e.getValue().forEach(System.out::print);
            System.out.println("}");
        });
    

    Output:

    1={11111}
    3={3}
    7={77}
    

提交回复
热议问题