在Java中,可以使用以下方式设置Map的初始值:

  1. 使用静态初始化块:
Map<String, Integer> map = new HashMap<String, Integer>() { {
    put('key1', 1);
    put('key2', 2);
    put('key3', 3);
}};
  1. 使用Collections工具类的方法:
Map<String, Integer> map = new HashMap<>();
map.put('key1', 1);
map.put('key2', 2);
map.put('key3', 3);
map = Collections.unmodifiableMap(map);
  1. 使用Java 9的新特性,使用Map.of方法:
Map<String, Integer> map = Map.of('key1', 1, 'key2', 2, 'key3', 3);

注意:Map.of方法在Java 9及以上版本可用。

这些方法都可以用来设置Map的初始值,并在需要时进行简写。选择使用哪种方法取决于你的需求和使用的Java版本。

Java Map 初始化值的简写方法

原文地址: https://www.cveoy.top/t/topic/pdwp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录