Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to initialize a SortedMap<Integer, String> with values already included in Java?

I'd like to do something like so

SortedMap<Integer, String> stuff = new TreeMap<Integer, String>({1:"a",2:"b"});

much like you would do in python but is that possible in Java, or is the only way to call .put() twice?

like image 636
asdf Avatar asked Jul 19 '26 20:07

asdf


1 Answers

Starting Java 9, you could do:

SortedMap<Integer, String> stuff = new TreeMap<>(Map.of(1, "a", 2, "b"));

Javadoc links:

TreeMap(Map<? extends K, ? extends V> m)

Map<K, V> of(K k1, V v1, K k2, V v2)

like image 183
M A Avatar answered Jul 21 '26 11:07

M A