Search code examples
javadata-structuresjava-8initializationsortedmap

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?


Solution

  • 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)