Linux 拨号vps windows公众号手机端

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

lewis 8年前 (2017-04-06) 阅读数 7 #程序编程
文章标签 Java

在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));

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

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门