Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
like image 262
tmeach Avatar asked Dec 01 '22 15:12

tmeach


1 Answers

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.

like image 164
David Conrad Avatar answered Dec 04 '22 09:12

David Conrad