gpt4 book ai didi

Java8 流 : Collect elements after a condition is met

转载 作者:IT老高 更新时间:2023-10-28 21:11:27 27 4
gpt4 key购买 nike

我的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"}]

最佳答案

在 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());

关于Java8 流 : Collect elements after a condition is met,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52269422/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com