有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在映射中保持插入顺序。工厂?

Java9提供了Map.of()特性,可以轻松创建具有固定值的映射

问题:我想创建一个保持插入顺序的映射,如LinkedHashMap。那家工厂有可能吗?至少map.of()不显示顺序


共 (3) 个答案

  1. # 1 楼答案

    ^{}(emphasis mine)的Java apidoc所述:

    Unmodifiable Maps

    The Map.of, Map.ofEntries, and Map.copyOf static factory methods provide a convenient way to create unmodifiable maps. The Map instances created by these methods have the following characteristics:

    • ...
    • The iteration order of mappings is unspecified and is subject to change.
    • ...

    不幸的是,Java API中没有等效的便利方法来创建LinkedHashMap。如果想要一致的迭代顺序,那么需要手动创建一个LinkedHashMap并填充它(如果需要,还需要使用Collections.unmodifiableMap包装它)

    考虑创建自己的便利方法,该方法等效于^ {CD5>},但以一致的迭代顺序(或者找到一个已经提供的现有库)。p>

  2. # 2 楼答案

    实际上,没有像LinkedHashMap::of这样的工厂方法,而且Map本身也没有顺序,所以我看到的唯一方法是,如果确实需要的话,构建一个LinkedHashMap

    顺便说一句,从the JEP itself

    Static factory methods on concrete collection classes (e.g., ArrayList, HashSet) have been removed from this proposal ...

    There is another wrinkle, which is that static methods on classes are inherited by subclasses. Suppose a static factory method HashMap.of() were to be added. Since LinkedHashMap is a subclass of HashMap, it would be possible for application code to call LinkedHashMap.of(). This would end up calling HashMap.of(), not at all what one would expect!

    这里的要点是static方法是继承的,但不可重写,因此,如果这样一个方法被添加到HashMap中,它可能不会在LinkedHashMap中被重写

    如果您可以使用guava,那么您可以使用ImmutableMap,它被记录为:

    An immutable, hash-based Map with reliable user-specified iteration order...

  3. # 3 楼答案

    你也可以使用vavr。io以以下方式进行:

    Map<String, String> mapPreservingInsertionOrder = io.vavr.collection.LinkedHashMap.of("key1", "val1", "key2", "val2").toJavaMap();