温馨提示×

java如何往map里放数据

小亿
370
2023-08-09 00:42:31
栏目: 编程语言

Java中往Map里放数据有多种方法,其中常用的有以下几种:

  1. 使用put方法:使用Map的put(key, value)方法可以将指定的键值对存放到Map中。示例代码如下:
Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", 2);
  1. 使用putAll方法:使用Map的putAll(map)方法可以将一个Map的所有键值对存放到当前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方法将数据存放到Map中。示例代码如下:
List<String> list = Arrays.asList("key1", "key2", "key3");
Map<String, Integer> map = list.stream()
.collect(Collectors.toMap(Function.identity(), String::length));
  1. 使用其他实现类的构造方法:除了HashMap,还可以使用其他实现类的构造方法来创建Map对象并存放数据。例如,使用TreeMap可以按键的自然顺序进行排序:
Map<String, Integer> map = new TreeMap<>();
map.put("key1", 1);
map.put("key3", 3);
map.put("key2", 2);

以上就是Java中往Map里放数据的几种常用方法,根据具体的需求选择合适的方法即可。

0