在Stream的地图函数中更改字段的值

时间:2018-09-19 07:13:06

标签: java java-8 functional-programming java-stream

我想更改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));

2 个答案:

答案 0 :(得分:11)

您不会将Stream<MenuAlertNotification>转换为Stream<Boolean>,所以请不要使用应该是 mapnon-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是终端操作)。

另外,传递给mapFunction应该是non-interferingstateless,因此您应确保setRead方法兼有。< / p>