问题描述
我有两个字符串数组.一种简称.
I have two String arrays. One having short name.
// days short name
String[] shortNames = {"SUN", "MON", "...", "SAT"};
另一个名字很长.
// days long name
String[] longNames = {"SUNDAY", "MONDAY", "....", "SATURDAY"};
两者都具有相同数量的元素.如何在 HashMap 中将短名称映射为 KEY,将长名称映射为 VALUE?
Both having same number of elements. How can I map short name as KEY and long name as VALUE in HashMap?
HashMap<String, String> days = new HashMap<>();
我知道,我可以通过循环来制作.有没有更好的办法?
I know, I can make by looping. Is there a better way?
推荐答案
有很多方法可以做到这一点.一个相当容易理解和应用的方法是使用 Java 8 流和收集器从索引流映射到键值对:
There are lots of ways you can do this. One that is fairly easy to understand and apply is using Java 8 streams and collectors to map from a stream of indices to key value pairs:
Map<String, String> days = IntStream.range(0, shortNames.length).boxed()
.collect(Collectors.toMap(i -> shortNames[i], i -> longNames[i]));
有一些第三方 Java 库包含一个zip"函数,用于获取两个流并生成从一个流到另一个流的映射.但实际上,它们只是实现与上述代码相同的事情的更简洁的方法.
There are some third party Java libraries that include a 'zip' function to take two streams and produce a map from one to the other. But really they are just neater ways of achieving the same thing as the code above.
这篇关于如何在 Java 中将两个数组映射到一个 HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!