跳转至

Map集合

Map 集合

1. Map

新增数据

Map<String, String> stkPortMap = new HashMap<>();
stkPortMap.put("张三", "苹果");
stkPortMap.put("张三","香蕉");
stkPortMap.put("李四", "苹果");
stkPortMap.put("李四","苹果");
System.out.println("stkPortMap>>>" + stkPortMap);
// stkPortMap>>>{李四=[苹果], 张三=[苹果, 香蕉]}

循环数据

System.out.println("entrySet>>>" + stkPortMap.entrySet());
// entrySet>>>[key1=B, key3=A, key4=C]
System.out.println("keySet>>>" + stkPortMap.keySet()); 
// keySet>>>[key1, key3, key4]
System.out.println("values>>>" + stkPortMap.values());
// values>>>[B, A, C]

2. Map>

新增数据

Map<String, List<String>> stkPortMap = new HashMap<>();
stkPortMap.computeIfAbsent("张三", k -> new ArrayList<>()).add("苹果");
stkPortMap.computeIfAbsent("张三", k -> new ArrayList<>()).add("香蕉");
stkPortMap.computeIfAbsent("李四", k -> new ArrayList<>()).add("苹果");
stkPortMap.computeIfAbsent("李四", k -> new ArrayList<>()).add("苹果");
System.out.println("stkPortMap>>>" + stkPortMap);
// stkPortMap>>>{李四=[苹果, 苹果], 张三=[苹果, 香蕉]}

循环数据

使用 Lambda 表达式和 Java 8 的流(Stream)API
// 获取key的Map集合
List<String> keySet = new ArrayList<String>(stkPortMap.keySet());
// 获取value的Map集合
List<String> valueSet = stkPortMap.values().stream()
.flatMap(List::stream)
.collect(Collectors.toList());
// 获取key的Map集合后去重
List<String> valueSet2 = stkPortMap.values().stream()
.flatMap(List::stream).distinct()
.collect(Collectors.toList());

System.out.println("keySet>>>>" + keySet);
System.out.println("valueSet>>>>" + valueSet);
System.out.println("去重后valueSet>>>>" + valueSet2);

// keySet>>>>[李四, 张三]
// valueSet>>>>[苹果, 苹果, 苹果, 香蕉]
// valueSet2>>>>[苹果, 香蕉]
for 循环
// 不去重
for (Map.Entry<String, List<String>> entry : stkPortMap.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

// 李四: [苹果, 苹果]
// 张三: [苹果, 香蕉]


// 去重
  for (Map.Entry<String, List<String>> entry : stkPortMap.entrySet()) {
      // 使用 LinkedHashSet 去重并保持插入顺序
      Set<String> set = new LinkedHashSet<>(entry.getValue());
      // 将去重后的集合转换回 List
      entry.setValue(new ArrayList<>(set));
      System.out.println(entry.getKey() + ": " + entry.getValue());
  }

// 李四: [苹果]
// 张三: [苹果, 香蕉]