将嵌套的 foreach 重构为 Java 8 流嵌套、重构、foreach、Java

由网友(- 孤独成瘾 -)分享简介:假设内部循环满足一个条件,我有两个列表,我循环遍历它们以填充最终列表.I have two lists that I loop through to populate a final list, given that the inner loop satisfies a condition.private List...

假设内部循环满足一个条件,我有两个列表,我循环遍历它们以填充最终列表.

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.

阅读全文

相关推荐

最新文章