Java8 流:满足条件后收集元素

2022-09-01 13:50:36

我的POJO如下

class EventUser {
  private id;
  private userId;
  private eventId;
}

我检索事件用户对象,如下所示:

List<EventUser> eventUsers = eventUserRepository.findByUserId(userId);

假设“事件用户”如下所示:

[
{"id":"id200","userId":"001","eventId":"1010"},
{"id":"id101","userId":"001","eventId":"4212"},
{"id":"id402","userId":"001","eventId":"1221"},
{"id":"id301","userId":"001","eventId":"2423"},
{"id":"id701","userId":"001","eventId":"5423"},
{"id":"id601","userId":"001","eventId":"7423"}
]

使用流,并且在不使用任何中间变量的情况下,如何在给定 EventUser.id 后过滤和收集事件:例如:

List<EventUser> filteredByOffSet = eventUsers.stream.SOMEFILTER_AND_COLLECT("id301");

结果应为:

[{"id":"id301","userId":"001","eventId":"2423"},
{"id":"id701","userId":"001","eventId":"5423"},
{"id":"id601","userId":"001","eventId":"7423"}]

答案 1

在Java 8中,你需要一个有状态过滤器

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));
}

注意:这仅对单线程流有意义。

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

答案 2

使用 Java 9 中的“dropWhile”。


推荐