How to use Java 8 streams to find all values preceding a larger value?

后端 未结 6 904
伪装坚强ぢ
伪装坚强ぢ 2020-12-29 18:57

Use Case

Through some coding Katas posted at work, I stumbled on this problem that I\'m not sure how to solve.

Using Java 8 Streams, given a

6条回答
  •  我在风中等你
    2020-12-29 19:43

    It's not a one-liner (it's a two-liner), but this works:

    List result = new ArrayList<>();
    values.stream().reduce((a,b) -> {if (a < b) result.add(a); return b;});
    

    Rather than solving it by "looking at the next element", this solves it by "looking at the previous element, which reduce() give you for free. I have bent its intended usage by injecting a code fragment that populates the list based on the comparison of previous and current elements, then returns the current so the next iteration will see it as its previous element.


    Some test code:

    List result = new ArrayList<>();
    IntStream.of(10, 1, 15, 30, 2, 6).reduce((a,b) -> {if (a < b) result.add(a); return b;});
    System.out.println(result);
    

    Output:

    [1, 15, 2]
    

提交回复
热议问题