javajava-11

any way to declare an immutable linkedhashmap in Java 11


If I want to declare a map of constants, with java 11 I can do this:

Map<String, String> map = Map.of(
    key, value,
    key, value,
    etc. etc
)

For my purpose, I need a LinkedHashMap because I need to keep safe the order in which the key value couples are defined, mainly because I need to stream and find first element in the map.

Something like:

return map.entrySet().stream()
          .filter(o -> o.getValue != null))
          .findFirst()
          .map(Map.Entry::getKey)

Any hints?


Solution

  • What about this?

    Map<String, String> map = new LinkedHashMap<>();
    map.put( "key1", "value1" );
    map.put( "key2", "value2" );
    …
    map = Collections.unmodifiableMap( map );
    

    You cannot use Map.of() as this would not preserve the sequence of entry. In addition, Map.of() will not accept null values, neither for the key nor for the value. And according to the second code snippet you will expect some keys that are linked to null.