如何在 Java 中将两个数组映射到一个 HashMap?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30339679/
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-11-02 16:56:27  来源:igfitidea点击:

How to map two arrays to one HashMap in Java?

javaarraysarraylisthashmap

提问by Madan Sapkota

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

Both having same number of elements. How can I map short name as KEY and long name as VALUE in HashMap?

两者都具有相同数量的元素。如何在 HashMap 中将短名称映射为 KEY,将长名称映射为 VALUE?

HashMap<String, String> days = new HashMap<>();

I know, I can make by looping. Is there a better way?

我知道,我可以通过循环来制作。有没有更好的办法?

回答by sprinter

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:

有很多方法可以做到这一点。一个相当容易理解和应用的方法是使用 Java 8 流和收集器从索引流映射到键值对:

Map<String, String> days = IntStream.range(0, shortNames.length).boxed()
    .collect(Collectors.toMap(i -> shortNames[i], i -> longNames[i]));

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 库包含一个“zip”函数来获取两个流并生成一个从一个流到另一个流的映射。但实际上,它们只是实现与上述代码相同的事情的更简洁的方法。

回答by Jens Piegsa

The accepted answerdid not work for me, as the IntStreamdoes not provide a one-argument collectmethod.

接受的答案没有工作对我来说,因为IntStream不提供一个参数的collect方法。

To nevertheless benefit from the toMapcollector you have to box the intprimitives into Integerobjects first. If you like to preserve the element order, use the extended version of toMaptogether with LinkedHashMap::newlike shown below:

尽管如此,为了从toMap收集器中受益,您必须首先将int基元装箱到Integer对象中。如果您想保留元素顺序,使用的扩展版本toMap连同LinkedHashMap::new像图所示:

package learning.java8;

import static java.util.stream.Collectors.*;
import static org.junit.Assert.*;

import java.time.DayOfWeek;
import java.time.format.TextStyle;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.stream.IntStream;

import org.junit.Test;

public class IntStreamLT {

    @Test
    public void q30339679() {

        final String[] shortNames = getDayOfWeekNamesInEnglish(TextStyle.SHORT);
        final String[] longNames = getDayOfWeekNamesInEnglish(TextStyle.FULL);

        final Map<String, String> days = IntStream.range(0, shortNames.length).boxed()
                .collect(toMap(i -> shortNames[i], i -> longNames[i]));

        System.out.println(days);

        final Map<String, String> sorted = IntStream.range(0, shortNames.length).boxed()
                .collect(toMap(
                        i -> shortNames[i], i -> longNames[i],
                        (i, j) -> i, LinkedHashMap::new));

        System.out.println(sorted);

        assertEquals("{Mon=Monday, Tue=Tuesday, Wed=Wednesday, Thu=Thursday, "
                + "Fri=Friday, Sat=Saturday, Sun=Sunday}", sorted.toString());
    }

    private static String[] getDayOfWeekNamesInEnglish(final TextStyle style) {

        return Arrays.stream(DayOfWeek.values())
                .map(day -> day.getDisplayName(style, Locale.ENGLISH))
                .toArray(String[]::new);
    }
}

see also: Why don't primitive Stream have collect(Collector)?

另请参阅:为什么原始 Stream 没有 collect(Collector)?

回答by alex

You can use org.apache.commons.lang3.ArrayUtils.

您可以使用org.apache.commons.lang3.ArrayUtils.

Here is an example:

下面是一个例子:

Map colorMap = ArrayUtils.toMap(new String[][] {
    {"RED", "#FF0000"},
    {"GREEN", "#00FF00"},
    {"BLUE", "#0000FF"}});