如何使用stream - Java 8将List转换为带索引的Map? [英] How to convert List to Map with indexes using stream - Java 8?

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

问题描述

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

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.

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

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