How to use if-else logic in Java 8 stream forEach(如何在 Java 8 流 forEach 中使用 if-else 逻辑)
问题描述
下面的 2 个流调用中显示了我想要做的事情.我想根据某些条件将一个集合拆分为 2 个新集合.理想情况下,我想在 1 中执行此操作.我已经看到了用于流的 .map 函数的条件,但找不到 forEach 的任何内容.实现我想要的最佳方式是什么?
What I want to do is shown below in 2 stream calls. I want to split a collection into 2 new collections based on some condition. Ideally I want to do it in 1. I've seen conditions used for the .map function of streams, but couldn't find anything for the forEach. What is the best way to achieve what I want?
animalMap.entrySet().stream()
.filter(pair-> pair.getValue() != null)
.forEach(pair-> myMap.put(pair.getKey(), pair.getValue()));
animalMap.entrySet().stream()
.filter(pair-> pair.getValue() == null)
.forEach(pair-> myList.add(pair.getKey()));
推荐答案
只需将条件放入 lambda 本身,例如
Just put the condition into the lambda itself, e.g.
animalMap.entrySet().stream()
.forEach(
pair -> {
if (pair.getValue() != null) {
myMap.put(pair.getKey(), pair.getValue());
} else {
myList.add(pair.getKey());
}
}
);
当然,这假定两个集合(myMap 和 myList)都在上述代码之前声明和初始化.
Of course, this assumes that both collections (myMap and myList) are declared and initialized prior to the above piece of code.
更新:使用 Map.forEach 使代码更短,更高效和可读,如 Jorn Vernee 好心建议:
Update: using Map.forEach makes the code shorter, plus more efficient and readable, as Jorn Vernee kindly suggested:
animalMap.forEach(
(key, value) -> {
if (value != null) {
myMap.put(key, value);
} else {
myList.add(key);
}
}
);
这篇关于如何在 Java 8 流 forEach 中使用 if-else 逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Java 8 流 forEach 中使用 if-else 逻辑
基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 存储 20 位数字的数据类型 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
