猿问

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

我的POJO如下


class EventUser {

  private id;

  private userId;

  private eventId;

}

我按如下方式检索 EventUser 对象:


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

说'eventUsers'如下:


[

{"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"}]


慕姐4208626
浏览 288回答 3
3回答

郎朗坤

在 Java 8 中你需要一个有状态的过滤器public static <T> Predicate<T> from(Predicate<T> test) {&nbsp; &nbsp; boolean[] found = { false };&nbsp; &nbsp; // once found, always true&nbsp; &nbsp; return t -> found[0] || (found[0] = test.test(t));}注意:这仅对单线程流有意义。List<EventUser> filteredByOffSet =&nbsp;&nbsp; &nbsp; &nbsp;eventUsers.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.filter(from(e -> "id301".equals(e.getId()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.toList());

万千封印

使用Java 9 中的“&nbsp;dropWhile&nbsp;”。

守候你守候我

先找到搜索项的索引:int asInt = IntStream.range(0, list.size())&nbsp; &nbsp; .filter(userInd-> list.get(userInd).equals(<criteria>))&nbsp; &nbsp; .findFirst()&nbsp; &nbsp; .getAsInt();获取索引前后的项目:list.stream().skip(asInt).collect(Collectors.toList());
随时随地看视频慕课网APP

相关分类

Java
我要回答