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

后端 未结 5 1094
无人共我
无人共我 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条回答
  •  -上瘾入骨i
    2020-12-09 16:50

    Things would be easier if your input is located in the random-access list. This way you can utilize good old List.subList method like this:

    List list = Arrays.asList("a", "b", "err1", "c", "d", "err2", "e", 
         "f", "g", "h", "err3", "i", "j");
    
    Map map = IntStream.range(0, list.size()-1)
        .mapToObj(i -> list.subList(i, i+2))
        .filter(l -> l.get(0).startsWith("err"))
        .collect(Collectors.toMap(l -> l.get(0), l -> l.get(1)));
    

    The same thing could be done with already mentioned StreamEx library (written by me) in a little bit shorter manner:

    List list = Arrays.asList("a", "b", "err1", "c", "d", "err2", "e", 
         "f", "g", "h", "err3", "i", "j");
    
    Map map = StreamEx.ofSubLists(list, 2, 1)
        .mapToEntry(l -> l.get(0), l -> l.get(1))
        .filterKeys(key -> key.startsWith("err"))
        .toMap();
    

    Though if you don't want third-party dependency, the poor Stream API solution looks also not very bad.

提交回复
热议问题