基于贝叶斯优化的卷积神经网络-门控循环单元回归预测模型及评估指标 - BO-CNN-GRU B...
2025/12/25 21:58:21
在Java中,你可以通过几种方式实现这个逻辑。以下是几种常见的实现方法:
Map<String, List<String>> map = new HashMap<>(); public void addValue(String key, String value) { if (map.containsKey(key)) { map.get(key).add(value); } else { List<String> newList = new ArrayList<>(); newList.add(value); map.put(key, newList); } }Map<String, List<String>> map = new HashMap<>(); public void addValue(String key, String value) { List<String> list = map.getOrDefault(key, new ArrayList<>()); list.add(value); map.put(key, list); }Map<String, List<String>> map = new HashMap<>(); public void addValue(String key, String value) { map.computeIfAbsent(key, k -> new ArrayList<>()).add(value); }Map<String, List<String>> map = new HashMap<>(); public void addValue(String key, String value) { map.putIfAbsent(key, new ArrayList<>()); map.get(key).add(value); }import java.util.*; public class MapExample { public static void main(String[] args) { // 使用方法3:computeIfAbsent(最简洁) Map<String, List<String>> map = new HashMap<>(); addToMap(map, "fruit", "apple"); addToMap(map, "fruit", "banana"); addToMap(map, "vegetable", "carrot"); addToMap(map, "fruit", "orange"); System.out.println(map); // 输出: {vegetable=[carrot], fruit=[apple, banana, orange]} } // 使用 computeIfAbsent public static void addToMap(Map<String, List<String>> map, String key, String value) { map.computeIfAbsent(key, k -> new ArrayList<>()).add(value); } }如果你需要处理不同类型的数据,可以使用泛型:
public class MapUtils { // 通用方法 public static <K, V> void addToListInMap(Map<K, List<V>> map, K key, V value) { map.computeIfAbsent(key, k -> new ArrayList<>()).add(value); } // 使用示例 public static void main(String[] args) { Map<String, List<Integer>> intMap = new HashMap<>(); Map<String, List<Double>> doubleMap = new HashMap<>(); Map<String, List<Object>> objectMap = new HashMap<>(); addToListInMap(intMap, "scores", 100); addToListInMap(doubleMap, "prices", 19.99); addToListInMap(objectMap, "items", "item1"); } }如果需要在多线程环境中使用:
Map<String, List<String>> concurrentMap = new ConcurrentHashMap<>(); public void addValueSafely(String key, String value) { // 使用 ConcurrentHashMap 的 computeIfAbsent concurrentMap.computeIfAbsent(key, k -> Collections.synchronizedList(new ArrayList<>()) ).add(value); }推荐使用方法3(computeIfAbsent),因为:
代码最简洁
避免多次访问Map
性能较好
是原子操作(在多线程环境下更安全)
如果你使用的是Java 8之前的版本,可以使用方法1,虽然代码稍长,但兼容性最好。