Java中map初始化赋值的方法是什么

842
2024/2/7 13:40:11
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中,有多种方法可以初始化和赋值给Map对象。以下是一些常见的方法:

  1. 使用字面量初始化和赋值:
Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", 2);
  1. 使用Map的实现类的构造函数初始化和赋值:
Map<String, Integer> map = new HashMap<>(Map.of("key1", 1, "key2", 2));

或者:

Map<String, Integer> map = new HashMap<>(Map.ofEntries(
    Map.entry("key1", 1),
    Map.entry("key2", 2)
));
  1. 使用Map的实现类的putAll()方法将另一个Map对象的内容复制到新的Map对象中:
Map<String, Integer> originalMap = new HashMap<>();
originalMap.put("key1", 1);
originalMap.put("key2", 2);

Map<String, Integer> newMap = new HashMap<>();
newMap.putAll(originalMap);
  1. 使用Java 8的Stream API来初始化和赋值:
Map<String, Integer> map = Stream.of(
    new AbstractMap.SimpleEntry<>("key1", 1),
    new AbstractMap.SimpleEntry<>("key2", 2)
).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

以上是一些常见的方法,根据具体需求和使用场景,可以选择适合的初始化和赋值方法。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java中setbackgroundcolor怎么设置