![](/img/trans.png)
[英]Does a Java compiler optimize ad hoc instances of `Set.of`, `List.of`, and `Map.of` in loops as constants
[英]Create mutable collections (Map.of and List.of)
看起來Map.of()
和List.of()
都創建了不可變的集合。 這很有用,但我正在尋找一種有時使用工廠方法創建可變集合的方法。
當我嘗試: HashMap.of()
我得到這個錯誤:
靜態方法只能在包含接口類上調用
HashMap
具有可以使用另一個Map
的構造函數,因此您可以通過將Map.of(...)
生成的內容傳遞給它來創建HashMap
:
HashMap<String, String> map = new HashMap<>(Map.of("k1", "v1", "k2", "v2"));
對於ArrayList
和List.of(...)
同樣List.of(...)
。
我在 utils 類中使用了一個自定義方法。 請嘗試,它可以正常工作。
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));
}
此外,您可以在成對數量的參數上添加驗證或添加邏輯以根據您的需要替換“空”值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.