Java Stream: is there a way to iterate taking two elements a time instead of one?

后端 未结 5 1095
无人共我
无人共我 2020-12-09 16:22

Let\'s say we have this stream

Stream.of(\"a\", \"b\", \"err1\", \"c\", \"d\", \"err2\", \"e\", \"f\", \"g\", \"h\", \"err3\", \"i\", \"j\");
5条回答
  •  借酒劲吻你
    2020-12-09 16:38

    Here's a simple one liner using an off-the-shelf collector:

    Stream stream = Stream.of("a", "b", "err1", "c", "d", "err2", "e", "f", "g", "h", "err3", "i", "j");
    
    Map map = Arrays.stream(stream
            .collect(Collectors.joining(",")).split(",(?=(([^,]*,){2})*[^,]*$)"))
        .filter(s -> s.startsWith("err"))
        .map(s -> s.split(","))
        .collect(Collectors.toMap(a -> a[0], a -> a[1]));
    

    The "trick" here is to first join all terms together into a single String, then split it into Strings of pairs, eg "a,b", "err1,c", etc. Once you have a stream of pairs, processing is straightforward.

提交回复
热议问题