我想更改Stream
中字段的值。我试图在.map
中进行更改,但出现编译错误
令牌语法错误,构造放置错误
流:
user.getMenuAlertNotifications()
.parallelStream()
.filter(not -> not.getUser().getId()==userId &&
notificationList.getIds().contains(not.getId()))
.map(not -> not.setRead(Boolean.TRUE) -> not)
.forEach(not -> menuService.save(not));
答案 0 :(得分:11)
您不会将Stream<MenuAlertNotification>
转换为Stream<Boolean>
,所以请不要使用应该是 map
的non-interfering ,stateless操作:
.filter(...)
.forEach(not -> {
not.setRead(Boolean.TRUE);
menuService.save(not);
});
在旁注中,not
传达了一个负面评论,有些人可能会感到困惑或陌生(我做到了)。我可以将lambda参数重命名为notification
,尽管您可以找到一个较短的选项。
顺便说一下,构造not -> not.set Read(Boolean.TRUE) -> not
可能会转换为一个完全有效的表达式:
.<Consumer<MenuAlertNotification>>map(not -> n -> n.setRead(Boolean.TRUE))
答案 1 :(得分:1)
.map(not -> {
not.setRead(Boolean.TRUE);
return not;
})
我认为peek
在这种情况下更有意义,因为您虽然返回了相同的元素:
peek(not -> not.setRead(Boolean.TRUE))
您也可以只使用true
代替Boolean.TRUE
。
请注意,这可能不会针对流中的所有元素运行(例如,如果发生短路,但是它将针对问题中流中未过滤的元素而运行,因为forEach
是终端操作)。
另外,传递给map
的Function
应该是non-interfering和stateless,因此您应确保setRead
方法兼有。< / p>