tmeach
tmeach

Reputation: 121

Create a map with key and value in one line in Java

Is there a way to create a map with keys and values at the same time (I mean a one-line code)? For example, I create a map named map, and I need to use the method "put" whenever I want to add a new pair of key/value. Is there a shorter way to populate a map when we create it?

Map<String, String> map = new HashMap<String, String>();
    map.put("A", "32");
    map.put("C", "34");
    map.put("T", "53");

Upvotes: 9

Views: 32267

Answers (2)

David Conrad
David Conrad

Reputation: 16359

Convenience Factory Methods for Collections

In Java 9 there are some new Map helper methods defined by JEP 269: Convenience Factory Methods for Collections.

Map<String, String> map = Map.of(
    "A", "32", 
    "C", "34", 
    "T", "53"
);

But this only works for up to 10 entries. For more than ten, use:

import static java.util.Map.entry;

Map<String, String> map = Map.ofEntries(
    entry("A", "32"), 
    entry("C", "34"), 
    entry("T", "53")
);

You could write similar helper methods if you needed to do it in earlier versions.

Note that unlike the code in the question, a Map created like this will not be modifiable.

Wrap it in new HashMap<>( ... ) if a mutable map is desired.

Upvotes: 26

Philzen
Philzen

Reputation: 4647

In Java 8 you can use the following methods which are explained here:

If you just need a quick immutable single-entry or empty map

Map<String, String> map = Collections.singletonMap("A", "32");
Map<String, String> map = Collections.emptyMap();

Using Streams

Suppose you have your data in an ArrayList of objects that contain your Data that can be accessed with arbitrary getters, you can use the Streams API:

List<Data> dataList = new ArrayList<>();
// .... populate data list
Map<String, Integer> nameToAge = dataList.stream().collect(
    Collectors.toMap(Data::getFooAsKey, Data::getBarAsValue)
);

...or using an inline map approach (if you don't have/need/want to create dataList):

Map<String, Integer> map = Stream.of( 
    new Data("A", "32"), new Data("C", "34"), new Data("C", "34")
).collect(Collectors.toMap(User::getFooAsKey, User::getBarAsValue));

Anonymous Subclass (discouraged)

Map<String, String> map = new HashMap<String, String>() {{
    put("A", "32");
    put("C", "34");
    put("T", "53");
}};

As this method can cause memory leaks it is strongly discouraged.

Using Guava

Map<String, String> immutableMap = Maps.newHashMap(
    ImmutableMap.of("A", "32", "C", "34", "T", "53")
);

Starting with Java 9 there's superior syntactic sugar available, as outlined in David's answer.

Upvotes: 12

Related Questions