本文介绍了Java8 Stream:满足条件后收集元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的POJO如下
class EventUser {
private id;
private userId;
private eventId;
}
我按如下方式检索EventUser对象:
I retrieve EventUser object as follows:
List<EventUser> eventUsers = eventUserRepository.findByUserId(userId);
假设'eventUsers'如下:
Say the 'eventUsers' is as follows:
[
{"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之后过滤和收集事件:
ex:
Using streaming, and without using any intermediate variable , how can I filter and collect events after a given EventUser.id:ex:
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"}]
推荐答案
在Java 8中,您需要一个有状态过滤器
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());
这篇关于Java8 Stream:满足条件后收集元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!