Java 中处理器友好的方式从 2 个映射的组合映射中删除重复值,无论键如何

问题描述 投票:0回答:1

我有以下 2 个 Java 地图。

 Map<String, String> carColors = new HashMap<>();
 carColors.put("FirstCar", "Blue");
 carColors.put("SecondCar", "Yellow");

 Map<String, String> colorsOfCars = new HashMap<>();
 colorsOfCars.put("FirstCar", "Yellow");
 colorsOfCars.put("SecondCar", "Blue");

 //duplicateMaps to avoid concurrency Issues
 Map<String, String> dup1 = new HashMap<>(carColors);
 Map<String, String> dup2 = new HashMap<>(colorsOfCars);

我正在尝试创建一个映射,无论键如何,都会删除任何匹配的值。在上面的汽车示例中,两张地图都有一辆蓝色和一辆黄色汽车。

我已经尝试过下面的方法,但这对于大型数据集来说是相当Java密集型的。

carColorsMap.entrySet().forEach(carColorEntry -> {
  colorsOfCars.entrySet().forEach(colorCarEntry -> {
     if(carColorEntry.getValue().toString().equalsIgnoreCase(colorsOfCars.getValue().toString()){
       dup1.remove(carColorEntry.getKey());
       dup2.remove(colorsOfCarsEntry.getKey()); 
      }
   });
});

如果有更高效的方法,请分享。谢谢

java maps
1个回答
0
投票

也许以下方法可以帮助降低运行两个循环的复杂性。

        // Create a set of unique values from both maps
        Set<String> uniqueValues = new HashSet<>(dup1.values());
        uniqueValues.addAll(dup2.values());

        // Remove entries with values found more than once
        uniqueValues.forEach(value -> {
                dup1.values().removeIf(val -> val.equals(value));
                dup2.values().removeIf(val -> val.equals(value));
        });
© www.soinside.com 2019 - 2024. All rights reserved.