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?
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:
The following holds true according to the Javadoc of SortedMap
from both Java-8 and Java-14. It reads for a SortedMap
:
The expected "standard" constructors for all sorted map implementations are:
A void (no arguments) constructor, which creates an empty sorted map sorted according to the natural ordering of its keys.
A constructor with a single argument of type
Comparator
, which creates an empty sorted map sorted according to the specified comparator.A constructor with a single argument of type
Map
, which creates a new map with the same key-value mappings as its argument, sorted according to the keys' natural ordering.A constructor with a single argument of type
SortedMap
, which creates a new sorted map with the same key-value mappings and the same ordering as the input sorted map.
and on the basis of (3), you can simply initialize a SortedMap
implementation wrapping another Map
initialization as a constructor argument. There are a lot of options in this Q&A that match with other suggestions here.
In Java 8:
Stream.of(new SimpleEntry<>(1, "a"), new SimpleEntry<>(2, "b"))
.collect(
Collectors.toMap(
Entry::getKey, Entry::getValue,
(a, b) -> { throw new IllegalStateException(); },
TreeMap::new);
(Yuk).
The answer by M Anouti holds good for only up to 10 entries. If you want to do it for more than 10 entries, you need to use Map.ofEntries(Map.entry(k, v), Map.entry(k, v) ...)
as shown below:
import static java.util.Map.entry;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
SortedMap<Integer, String> stuff = new TreeMap<>(
Map.ofEntries(entry(1, "a"), entry(2, "b"), entry(3, "c"), entry(4, "d"), entry(5, "e"), entry(6, "f"),
entry(7, "g"), entry(8, "h"), entry(9, "i"), entry(10, "j"), entry(11, "k"), entry(12, "l")));
System.out.println(stuff);
}
}
Output:
{1=a, 2=b, 3=c, 4=d, 5=e, 6=f, 7=g, 8=h, 9=i, 10=j, 11=k, 12=l}
There's double brace initializers:
Map stuff = new TreeMap<Integer, String>() {{
put(1, "a");
put(2, "b");
}};
System.out.println(stuff);
You can write this in one line if you want.
Although, I do not recommend this. Read here.