如何使用流将列表转换为带有索引的映射 - Java 8?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33138577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:23:03  来源:igfitidea点击:

How to convert List to Map with indexes using stream - Java 8?

javajava-8java-stream

提问by Letfar

I've created method whih numerating each character of alphabet. I'm learning streams(functional programming) and try to use them as often as possible, but I don't know how to do it in this case:

我已经创建了计算字母表中每个字符的方法。我正在学习流(函数式编程)并尝试尽可能频繁地使用它们,但在这种情况下我不知道该怎么做:

private Map<Character, Integer> numerateAlphabet(List<Character> alphabet) {
    Map<Character, Integer> m = new HashMap<>();
    for (int i = 0; i < alphabet.size(); i++)
        m.put(alphabet.get(i), i);
    return m;
}

So, how to rewrite it using streams of Java 8?

那么,如何使用 Java 8 的流来重写它呢?

采纳答案by Misha

Avoid stateful index counters like the AtomicInteger-based solutions presented in other answers. They will fail if the stream were parallel. Instead, stream over indexes:

避免使用像AtomicInteger其他答案中提出的基于解决方案的有状态索引计数器。如果流是并行的,它们将失败。相反,流过索引:

IntStream.range(0, alphabet.size())
         .boxed()
         .collect(toMap(alphabet::get, i -> i));

Above assumes that the incoming list is not supposed to have duplicate characters since it's an alphabet. If you have possibility of duplicate elements then multiple elements will map to same key and then you need to specify merge function. For example you can use (a,b) -> bor (a,b) ->aas the third parameter to toMapmethod.

上面假设传入的列表不应该有重复的字符,因为它是一个字母表。如果您有可能出现重复元素,那么多个元素将映射到同一个键,然后您需要指定合并函数。例如,您可以使用(a,b) -> b(a,b) ->a作为toMap方法的第三个参数。

回答by ashiquzzaman33

Using streams with AtomicIntegerin Java 8:

AtomicInteger在 Java 8 中使用流:

private Map<Character, Integer> numerateAlphabet(List<Character> alphabet) {
    AtomicInteger index = new AtomicInteger();
    return alphabet.stream().collect(
            Collectors.toMap(s -> s, s -> index.getAndIncrement(), (oldV, newV)->newV));
}

回答by Saravana

using AtomicInteger

使用 AtomicInteger

    AtomicInteger counter = new AtomicInteger();
    Map<Character, Integer> map = characters.stream()
            .collect(Collectors.toMap((c) -> c, (c) -> counter.incrementAndGet()));
    System.out.println(map);

回答by akhil_mittal

It is better to use Function.identity()in place of i->i:

最好使用Function.identity()代替i->i

IntStream.range(0, alphabet.size())
                .boxed()
                .collect(toMap(alphabet::get, Function.identity()));