java如何往map里放數(shù)據(jù)

小億
507
2023-08-09 00:42:31
欄目: 編程語言

Java中往Map里放數(shù)據(jù)有多種方法,其中常用的有以下幾種:

  1. 使用put方法:使用Map的put(key, value)方法可以將指定的鍵值對(duì)存放到Map中。示例代碼如下:
Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", 2);
  1. 使用putAll方法:使用Map的putAll(map)方法可以將一個(gè)Map的所有鍵值對(duì)存放到當(dāng)前Map中。示例代碼如下:
Map<String, Integer> map1 = new HashMap<>();
map1.put("key1", 1);
map1.put("key2", 2);
Map<String, Integer> map2 = new HashMap<>();
map2.put("key3", 3);
map2.put("key4", 4);
map1.putAll(map2);
  1. 使用Java 8的新特性:Java 8引入了Stream API,可以使用Stream的collect方法將數(shù)據(jù)存放到Map中。示例代碼如下:
List<String> list = Arrays.asList("key1", "key2", "key3");
Map<String, Integer> map = list.stream()
.collect(Collectors.toMap(Function.identity(), String::length));
  1. 使用其他實(shí)現(xiàn)類的構(gòu)造方法:除了HashMap,還可以使用其他實(shí)現(xiàn)類的構(gòu)造方法來創(chuàng)建Map對(duì)象并存放數(shù)據(jù)。例如,使用TreeMap可以按鍵的自然順序進(jìn)行排序:
Map<String, Integer> map = new TreeMap<>();
map.put("key1", 1);
map.put("key3", 3);
map.put("key2", 2);

以上就是Java中往Map里放數(shù)據(jù)的幾種常用方法,根據(jù)具體的需求選擇合適的方法即可。

0