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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With