Fabrizio Stellato
Fabrizio Stellato

Reputation: 1901

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?

Upvotes: 5

Views: 3379

Answers (2)

Eric
Eric

Reputation: 6354

I would recommend using Google Guava's ImmutableMap class. The order of the arguments is the same order in the Map when you iterate over it.

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

See the Guava Collections Documentation: https://github.com/google/guava/wiki/ImmutableCollectionsExplained#how

Upvotes: 1

tquadrat
tquadrat

Reputation: 4044

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.

Upvotes: 4

Related Questions