Java8 Stream : Collect elements after a condition is met

我怕爱的太早我们不能终老 提交于 2019-12-03 09:29:09

In Java 8 you need a stateful filter

public static <T> Predicate<T> from(Predicate<T> test) {
    boolean[] found = { false };
    // once found, always true
    return t -> found[0] || (found[0] = test.test(t));
}

NOTE: this only makes sense for single threaded streams.

List<EventUser> filteredByOffSet = 
     eventUsers.stream()
               .filter(from(e -> "id301".equals(e.getId()))
               .collect(Collectors.toList());

Use "dropWhile" from Java 9.

Find the index of the search item first:

int asInt = IntStream.range(0, list.size())
    .filter(userInd-> list.get(userInd).equals(<criteria>))
    .findFirst()
    .getAsInt();

Get items on and after the index:

list.stream().skip(asInt).collect(Collectors.toList());

You cant do that without using any intermediate variables. finding the position and iterate it to the end (see this question below that answer it more precisely) enter link description here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!