Java - How to create new Entry (key, value)

前端 未结 11 1526
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 09:55

I\'d like to create new item that similarly to Util.Map.Entry that will contain the structure key, value.

The problem is that

11条回答
  •  庸人自扰
    2020-11-27 10:04

    Starting from Java 9, there is a new utility method allowing to create an immutable entry which is Map#entry(Object, Object).

    Here is a simple example:

    Entry entry = Map.entry("foo", "bar");
    

    As it is immutable, calling setValue will throw an UnsupportedOperationException. The other limitations are the fact that it is not serializable and null as key or value is forbidden, if it is not acceptable for you, you will need to use AbstractMap.SimpleImmutableEntry or AbstractMap.SimpleEntry instead.

    NB: If your need is to create directly a Map with 0 to up to 10 (key, value) pairs, you can instead use the methods of type Map.of(K key1, V value1, ...).

提交回复
热议问题