更改Stream的map函数中字段的值

Nuñ*_*ada 5 java functional-programming java-8 java-stream

我想改变一个字段的值Stream.我试图改变它,.map但我得到了一个编译错误

令牌上的语法错误,错放的构造(s)

流:

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));
Run Code Online (Sandbox Code Playgroud)

And*_*lko 11

你是不是要改造Stream<MenuAlertNotification>Stream<Boolean>,所以不要使用map它应该是一个无干扰的,无状态的操作:

.filter(...)
.forEach(not -> {
    not.setRead(Boolean.TRUE);
    menuService.save(not);
});
Run Code Online (Sandbox Code Playgroud)

在旁注中,not传达了一些负面评论,有些人可能会感到困惑或奇怪(我做过).我会将lambda参数重命名为notification,但你可以找到一个更短的选项.


顺便说一句,构造not -> not.set Read(Boolean.TRUE) -> not可能会转换成一个完全有效的表达式:

.<Consumer<MenuAlertNotification>>map(not -> n -> n.setRead(Boolean.TRUE))
Run Code Online (Sandbox Code Playgroud)

  • `peek`会起作用 - 不知道这是不是一个好主意.不是它的目的. (4认同)