在Vavr库中,可以使用HashMap.of()
方法来创建一个非空的HashMap。以下是一个示例代码:
import io.vavr.collection.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = HashMap.of("key1", 1, "key2", 2, "key3", 3);
System.out.println(hashMap.get("key1")); // 输出:Some(1)
System.out.println(hashMap.get("key4")); // 输出:None
System.out.println(hashMap.containsKey("key2")); // 输出:true
System.out.println(hashMap.containsValue(3)); // 输出:true
System.out.println(hashMap.size()); // 输出:3
}
}
在上面的示例中,我们使用HashMap.of()
方法创建了一个包含三个键值对的HashMap对象。然后,我们可以使用get()
方法获取指定键的值,containsKey()
方法检查HashMap中是否包含指定的键,containsValue()
方法检查HashMap中是否包含指定的值,以及size()
方法获取HashMap的大小。
请注意,Vavr库中的HashMap是不可变的,这意味着一旦创建就不能修改。如果需要进行修改,可以使用put()
方法返回一个新的HashMap对象。