Refactoring a nested foreach into Java 8 stream(将嵌套的 foreach 重构为 Java 8 流)
问题描述
假设内部循环满足一个条件,我有两个列表,我循环遍历它们以填充最终列表.
I have two lists that I loop through to populate a final list, given that the inner loop satisfies a condition.
private List<Enum> getEnumFromType(List<Bean.Var> vars, List<Enum> enums) {
List<Enum> enumList = new ArrayList<>();
for (Bean.Var var : vars) {
String typeWithoutTypeIdentifierPrefix = var.getType().substring(1,var.getType().length());
for (Enum enumVal : enums) {
if (typeWithoutTypeIdentifierPrefix.equals(enumVal.getName())) {
if (!enumList.contains(enumVal)) {
enumList.add(enumVal);
}
}
}
}
return enumList;
}
我已经重构了代码以使用最新的 Java 8 流 api,我想出了这个:
I have refactored the code to use the latest Java 8 streaming api and I came up with this:
vars.stream().forEach(
var -> {
String typeWithoutPrimitiveIdentifier = var.getType().substring(1,var.getType().length());
enums.stream()
.filter(enumVal -> typeWithoutPrimitiveIdentifier(enumVal.getName()))
.forEach(enumVal -> {
if (!enumList.contains(enumVal)) {
enumList.add(enumVal);
}
});
}
);
我怎样才能更进一步删除嵌套的 foreach() 方法?
How could I take this a step further to remove the nested foreach() methods?
推荐答案
使用 stream().forEach(..)
并在里面调用 add
的问题forEach
(所以你改变了外部 enumList
实例)是如果有人并行转动流并且集合不是线程安全的,你很容易遇到并发问题.
The problem by using stream().forEach(..)
with a call to add
inside the forEach
(so you mutate the external enumList
instance) is that you can run easily into concurrency issues if someone turns the stream in parallel and the collection is not thread safe.
相反,您应该支持适用于可变归约的 collect 方法:
Instead you should favor the collect approach which is suited for mutable reductions:
private Set<Enum> getEnumFromType(List<Bean.Var> vars, List<Enum> enums) {
return vars.stream()
.map(var -> var.getType().substring(1))
.map(v -> enums.stream().filter(e -> v.equals(e.getName())).findAny())
.filter(Optional::isPresent)
.map(Optional::get)
.collect(toSet());
}
您可能还想构建映射 String ->枚举
预先避免多重过滤.
You may also want to build the mappings String -> Enum
upfront to avoid multiple filtering.
private Set<Enum> getEnumFromType(List<Bean.Var> vars, List<Enum> enums) {
Map<String, Enum> enumsName = enums.stream().collect(toMap(Enum::getName, e -> e, (e1, e2) -> e1));
return vars.stream()
.map(var -> var.getType().substring(1))
.map(enumsName::get)
.filter(Objects::nonNull)
.collect(toSet());
}
如果你真的想返回一个List
,你可以看看Collectors.collectingAndThen
.
If you really want to return a List
, you can look at Collectors.collectingAndThen
.
这篇关于将嵌套的 foreach 重构为 Java 8 流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将嵌套的 foreach 重构为 Java 8 流


基础教程推荐
- 不推荐使用 Api 注释的描述 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01