io.vavr.collection.HashMap可以使用地图界面吗?

Is it possible to use the map interface with io.vavr.collection.HashMap?

在尝试将 Vavr 的不可变映射 (io.vavr.collection.HashMap) 与 java.util.Map 接口一起使用时,我没有设法编译代码 - 至少不是通过使用io.vavr.collection.HashMap.

中的 .of() 静态方法

本质上这是我正在使用的 Maven 依赖项:

<dependency>
    <groupId>io.vavr</groupId>
    <artifactId>vavr</artifactId>
    <version>0.9.2</version>
</dependency>

与 Java 1.8

这是代码:

import io.vavr.collection.HashMap;

import java.util.Map;

public class EntityKeyMap {

    public static final Map<String, String> map = 
            HashMap.of("key1", "val1", "key2", "val2", "key3", "val3");

    private EntityKeyMap() {
    }
}

这是我收到的错误:

Incompatible types. Required Map but 'of' was inferred to HashMap: no instance(s) of type variable(s) K, V exist so that HashMap conforms to Map

关于如何将 io.vavr.collection.HashMap 的实例分配给 java.util.Map 的任何想法?这可能吗?

根据 io.vavr.collection.HashMap 文档,它实现了 java.util.Map 接口:

https://static.javadoc.io/io.vavr/vavr/0.9.2/io/vavr/collection/HashMap.html

网络上有一些例子似乎是可行的,例如 blog,您可以在其中找到此代码:

Map<String, String> map1
  = HashMap.of("key1", "val1", "key2", "val2", "key3", "val3");

toJavaMap 方法正是用于此目的:

Converts this Vavr Map to a java.util.Map while preserving characteristics like insertion order (LinkedHashMap) and sort order (SortedMap).

import io.vavr.collection.HashMap;

public class VavrPlayground {

   public static final HashMap<String, String> map =
       HashMap.of("key1", "val1", "key2", "val2", "key3", "val3");

   public void EntityKeyMap() {
      java.util.Map<String, String> jMap = map.toJavaMap();
   }

}

Vavr 的 HashMap 没有实现 JDK's Map interface. The Map interface it implements is vavr's own Map 接口。

与JDK的Map相反,vavr的Map表示一个不可变映射,HashMap being an efficient persistent map implementation based on Hash array mapped trie.

JDK Map 接口和 vavr Map 接口之间最根本的区别是 JDK 映射具有 mutate 地图的内部状态,而 vavr 的方法总是 return 一个新的 Map 实例(或者相同的实例,以防地图没有改变)。

比较 JDK 的 Map.put vs vavr's Map.put 方法签名。

JDKMap.put:

V put(K key, V value)

Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)
Returns: the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key, if the implementation supports null values.)

vavr Map.put:

Map<K,V> put(K key, V value)

Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced by the specified value.
Returns: A new Map containing these elements and that entry.

如果您需要 JDK 地图,您可以使用 Map.toJavaMap 转换 vavr 地图,但这将创建地图内容的完整副本,因为 [=55] 的可变性质=] map 与 vavr 的不可变方法不兼容。