将嵌套的foreach重构为Java 8流 [英] Refactoring a nested foreach into Java 8 stream

查看:132
本文介绍了将嵌套的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(..)在 forEach 内调用添加(这样你就可以改变外部 enumList instance)如果有人并行转换流并且集合不是线程安全的,你可以轻松地运行并发问题。

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.

相反你应该支持适用于可变减少的收集方法:

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());
}

如果你真的想要返回列表,你可以看看 Collectors.collectingAndThen

If you really want to return a List, you can look at Collectors.collectingAndThen.

这篇关于将嵌套的foreach重构为Java 8流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆