In Java 11 there is a set of static methods in java.util.Map that allow instantiation of AbstractImmutableMap:
static <K, V> Map<K, V> of(K k1, V v1) { return new Map1(k1, v1); }
static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2) { return new MapN(new Object[]{k1, v1, k2, v2}); }
// ... some more "vararg" static methods until 10 pairs (inclusive).
There's also another method, that does almost the same, except it is true-vararg:
static <K, V> Map<K, V> ofEntries(Map.Entry<? extends K, ? extends V>... entries) { /* impl here */ }
I want to use the latter method, as it allows to expand number of entries far past ten. The problem is, I don't know how to create Map.Entry. It has a lot of implementations in different Maps, but there is no new operator or static fabric method for it, whereas Map has it.
Map#ofEntries is also used internally in Map#copyOf, but I cannot find a way to use it without already existing Map implementation with some entries in it. :/
I've tried searching for it, but couldn't find an answer.
➥ So, my question is: how was it intended to use Map#ofEntries? Or there is a way to instantiate Map.Entry without writing my own implementation or using anonymous classes?
You can use the static Map#entry method to create a single, unmodifiable instance of Map.Entry:
Map<String, Integer> map = Map.ofEntries(Map.entry("One", 1), Map.entry("Two", 2));
Printing map can result in the following output:
{One=1, Two=2}
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