Search code examples
javaarraysarraylisthashmap

How to map two arrays to one HashMap in Java?


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<String, String> days = new HashMap<>();

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


Solution

  • 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]));
    

    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.