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

后端 未结 6 905
伪装坚强ぢ
伪装坚强ぢ 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:31

    That's not a pure Java8, but recently I've published a small library called StreamEx which has a method exactly for this task:

    // Find all numbers where the integer preceded a larger value.
    Collection numbers = Arrays.asList(10, 1, 15, 30, 2, 6);
    List res = StreamEx.of(numbers).pairMap((a, b) -> a < b ? a : null)
        .nonNull().toList();
    assertEquals(Arrays.asList(1, 15, 2), res);
    

    The pairMap operation internally implemented using custom spliterator. As a result you have quite clean code which does not depend on whether the source is List or anything else. Of course it works fine with parallel stream as well.

    Committed a testcase for this task.

提交回复
热议问题