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.