溫馨提示×

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

小億
358
2024-01-18 13:40:11
欄目: 編程語言

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

以上是一些常見的方法,根據具體需求和使用場景,可以選擇適合的初始化和賦值方法。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女