本文介绍了如何使用流将列表转换为带有索引的地图 - Java 8?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

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

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:

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

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

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) -> b or (a,b) ->a as the third parameter to toMap method.

这篇关于如何使用流将列表转换为带有索引的地图 - Java 8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 02:31