简体   繁体   English

将列表转换为地图 - foreach或stream?

[英]Transform a list into a map - foreach or streams?

I want to transform a List<String> into a Map<String, Integer> . 我想将List<String>转换为Map<String, Integer> The lists' values should serve as keys, and the map value will be statically initialized. 列表的值应作为键,地图值将静态初始化。

I want to keep the order of the list, thus using a LinkedHashMap , and ignore duplicates. 我想保持列表的顺序,因此使用LinkedHashMap ,并忽略重复。

Question: is there any advantage using the java8 stream API? 问题:使用java8 stream API有什么好处吗? Because, comparing the following, simply regarding the syntax I'd never go for the verbose stream api, but always sticking to the old foreach loop: 因为,比较以下内容,只是关于语法我永远不会去详细的流api,但总是坚持旧的foreach循环:

    //foreach
    Map<String, Integer> map = new LinkedHashMap<>();
    for (String k : abk) {
        if (k != null) map.put(k, STATIC_VAL);
    }

    //streams
    Map<String, Integer> map2 = abk.stream()
            .filter(Objects::nonNull)
            .collect(Collectors.toMap(
                        Function.identity(),
                        k -> STATIC_VAL,
                        (v1, v2) -> v1,
                        LinkedHashMap::new));

Would you stick to the old approach or go with new lambda expressions? 你会坚持使用旧方法还是使用新的lambda表达式?

For this simple case I would stick to the for loop. 对于这个简单的例子, 会坚持使用for循环。 It is faster too by the way (besides being more readable), Stream s do have a cost of the infrastructure that has to be used. 顺便说一句,它也更快(除了更具可读性), Stream确实需要使用基础设施的成本。 This new API is just a tool and as every tool is has pros/cons. 这个新API只是一个工具,因为每个工具都有优点/缺点。

Generally I tent to used stream api only when I have to - let's say that the List needs filtered or mapped to something else, etc - then the Stream usage would make sense. 通常我只在必须时使用流api - 让我们说List需要过滤或映射到其他东西等等 - 然后Stream使用是有意义的。 If there are multiple operations that have to be done, it would make code way more readable then doing the same thing with a loop; 如果有多个操作需要完成,那么使代码更容易阅读,然后用循环做同样的事情; but that's not always the case - as in your example. 但情况并非如此 - 如你的例子所示。

Parallelization (in case you really need it is another aspect). 并行化(如果你真的需要它是另一个方面)。 Simple for loops are not easily parallelized, but with streams this is a breeze. 简单的for循环不容易并行化,但对于流,这是一件轻而易举的事。

There's a variant on the traditional for loop that you can use as well: 您可以使用传统的for循环中的变体:

Map<String, Integer> map = new LinkedHashMap<>();
abk.forEach(k -> if (k != null) map.put(k, STATIC_VAL));

But it's just a matter of style. 但这只是风格问题。 Either this way or the traditional for loop looks good to me. 这种方式或传统的for循环对我来说都很好。 Using streams, on the other hand, is more verbose and less readable, IMO. 另一方面,使用流更简洁,更不易读,IMO。

You could write the for-each with stream. 您可以使用流编写for-each。 eg. 例如。

abk.stream()
    .filter(Object::notNull)
    .forEach(s->map.put(s, STATIC_VAL));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM