本文介绍了如何在Java中两个数组的一个HashMap的地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个字符串数组。有一个简短的名称。

I have two String arrays. One having short name.

// days short name
String[] shortNames = {"SUN", "MON", "...", "SAT"};

另外有长的名字。

The other having long name.

// days long name
String[] longNames = {"SUNDAY", "MONDAY", "....", "SATURDAY"};

双方有相同数目的元素。我该如何映射短名作为关键字和长名称作为HashMap的价值?

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)
    .collect(Collectors.toMap(i -> shortNames[i], i -> longNames[i]));

有,包括一个拉链功能采取两个流,并从一个到另一个产生地图一些第三方Java库。但实际上它们是实现同样的事情code以上只是简洁的方式。

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的地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 15:19