Java 11 immutable map: create Map.Entry

Xobotun :

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?

Jacob G. :

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}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=323634&siteId=1