我的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"}]
3 回答
郎朗坤
TA贡献1921条经验 获得超9个赞
在 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());
守候你守候我
TA贡献1802条经验 获得超10个赞
先找到搜索项的索引:
int asInt = IntStream.range(0, list.size())
.filter(userInd-> list.get(userInd).equals(<criteria>))
.findFirst()
.getAsInt();
获取索引前后的项目:
list.stream().skip(asInt).collect(Collectors.toList());
添加回答
举报
0/150
提交
取消