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

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

我想更改 Stream 中字段的值。我试图在 .map 中更改它,但出现编译错误

Syntax error on token(s), misplaced construct(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));

最佳答案

您不会转换 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))

关于java - 更改 Stream 的 map 函数中字段的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52400149/

相关文章:

java - 无法读取 JSON : Current token (VALUE_STRING) not numeric, 无法使用数值访问器

java - 类实例化与通过引用检索

java - 使用 HashMap、HashSet 等时覆盖 hashCode?

haskell - 使用 id 定义 fmap 并返回

c++ - C++11 中的函数式编程,F# 风格

java - 还在为使用 Java 中的 ArrayDeque 和线程做作业而苦恼吗?

java - 使用流 API 查找列表中项目的所有索引

java - 在 Java SE 8 API 中准备特定格式的 UTC 日期时无法解析 00 秒

java - 确定 future 的时区转换

通过条件给定的定界符将列表拆分为多个部分的 Pythonic 方法