[英]Create mutable collections (Map.of and List.of)
Looks like Map.of()
and List.of()
both create immutable collections.看起来
Map.of()
和List.of()
都创建了不可变的集合。 That's useful, but I am looking for a way to create mutable collections sometimes using a factory method.这很有用,但我正在寻找一种有时使用工厂方法创建可变集合的方法。
When I try: HashMap.of()
I get this error:当我尝试:
HashMap.of()
我得到这个错误:
Static method may be invoked on containing interface class only
静态方法只能在包含接口类上调用
HashMap
has a constructor that can take another Map
, so you can create a HashMap
by passing it whatever Map.of(...)
produces: HashMap
具有可以使用另一个Map
的构造函数,因此您可以通过将Map.of(...)
生成的内容传递给它来创建HashMap
:
HashMap<String, String> map = new HashMap<>(Map.of("k1", "v1", "k2", "v2"));
Likewise for ArrayList
and List.of(...)
. 对于
ArrayList
和List.of(...)
同样List.of(...)
。
I use a custom method inside of the utils class.我在 utils 类中使用了一个自定义方法。 Please try, it works correctly.
请尝试,它可以正常工作。
public static Map<String, Object> mutableMap(Object... args) {
return IntStream.iterate(0, i -> i < args.length, i -> i + 2)
.filter(i -> i + 1 < args.length)
.boxed()
.collect(toMap(i -> (String) args[i], i -> args[i + 1], (a, b) -> b, HashMap::new));
}
Also, you can add validation on paired number of arguments OR add logic to replace the 'null' value according to your requires.此外,您可以在成对数量的参数上添加验证或添加逻辑以根据您的需要替换“空”值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.