在 Java 11 中声明不可变 linkedhashmap 的任何方式

any way to declare an immutable linkedhashmap in Java 11

如果我想用 java 11 声明常量映射,我可以这样做:

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

为了我的目的,我需要一个 LinkedHashMap 因为我需要保证定义键值对的顺序安全,主要是因为我需要流式传输并找到第一个元素在地图上。

类似于:

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

有什么提示吗?

这个呢?

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

您不能使用 Map.of(),因为这不会保留条目的顺序。此外,Map.of() 不会接受 null 值,既不接受键也不接受值。根据第二个代码片段,您会期望一些链接到 null.

的键