gpt4 book ai didi

java - 比较 Java 中的两个 map

转载 作者:行者123 更新时间:2023-11-29 05:55:42 28 4
gpt4 key购买 nike

我希望能够比较两个数组(它们将保存相同 XML 但不同年龄的值,因此我可以查看是否进行了任何更改)。我有两个数组,一个包含我已解析的旧 XML 行的属性和值,另一个包含已解析的同一 XML 行的属性和最新版本。

例子:

Array1:                                                                         

rect x="220.00"
width="300.00"
id="rect_1"
y="180.00"
height="280.00"

Array2:

rect x="300.00"
width="400.00"
id="rect_1"
height="280.00"
info = "description"

etc etc

所以这里的变化是:

  • rect x 属性已从 220 (array1) 更改为 300 (array2)
  • width 属性已从 300 (array1) 更改为 400(array2)
  • Array2 获得了一个名为 info 的属性
  • y 已从 array2 中移除

我如何比较两个数组并显示这样的结果?基本上我希望它显示变化和差异。

这是我试过的代码:

Collection<String> listOne = Arrays.asList(array1);

Collection<String> listTwo = Arrays.asList(array);

Collection<String> similar = new HashSet<String>( listOne );
Collection<String> different = new HashSet<String>();
different.addAll( listOne );
different.addAll( listTwo );

similar.retainAll( listTwo );
different.removeAll( similar );

resultsBuff.append("\nDifferences: \n"+ different + "\n\nChanges: \n" + similar);

这段代码并没有完全按照我的意愿去做(如前所述)。

最佳答案

您别无选择,只能遍历两个数组。我会遍历属性、拆分键和值并为每个数组构建一个 HashMap。

Map<String, String> map1 = new HashMap<String, String>() 
for (String attribute : array1) {
String[] splitted = attribute.split("=");
map1.put(splitted[0], splitted[1]);
}

做同样的事情来创建 map2。

Map<String, String> map2 = new HashMap<String, String>(); 
...

遍历第一个 map 并验证键/值是否不同或存在于 map2 中以检测到属性删除。

for (String key : map1.keySet()) {    
if (!map2.containsKey(key)) {
System.out.println(key + "has been removed from Array2" )
} else if (!map1.get(key).equals(map2.get(key)) {
System.out.println(key + "attribute has changed from " + map1.get(key) + " to " + map2.get(key) );
}
}

遍历 map2 以检测新属性

for (String key : map2.keySet()) {    
if (!map1.containsKey(key)) {
System.out.println(key + "has been added to Array2" );
}

希望这对您有所帮助!

关于java - 比较 Java 中的两个 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12211753/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com