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