如何在Java中比较hashmap?
我有两个如何在Java中比较hashmap?,java,hashmap,Java,Hashmap,我有两个HashMaps,我想比较值的键,如果它们不同,则返回两个键之间的差异 public class AsciiCount { public static void main(String args[]) { String input = "Hello"; String input1 = "eHllo"; Store obj1= new Store();
HashMaps
,我想比较值的键,如果它们不同,则返回两个键之间的差异
public class AsciiCount {
public static void main(String args[]) {
String input = "Hello";
String input1 = "eHllo";
Store obj1= new Store();
String orderOfString = obj1.CheckOrder(input);
System.out.println(orderOfString);
HashMap inputLocation = obj1.getCharacterLocation(input);
HashMap input1Location = obj1.getCharacterLocation(input1);
System.out.println(inputLocation);
System.out.println(input1Location);
}
}
// OUTPUT of print
// inputLocation = {0=72, 1=101, 2=108, 3=108, 4=111}
// input1Location = {0=101, 1=72, 2=108, 3=108, 4=111}
示例
这里
在inputLocation
中72的键是0,但在input1Location
101键在inputLocation
中为1,但101键在input1Location
因此,输出应该是
2
(即更改的数量)您必须在两个对象HashMaps的keySet()上使用相等值来比较单个值。使用此选项,您可以比较/获取散列的密钥参数。在此之后,您必须获取HashMap的值以比较该值。但是如果需要比较整个散列,只需使用equals
您的代码将如下所示:
public class AsciiCount {
public static void main(String args[]) {
String input = "Hello";
String input1 = "eHllo";
Store obj1= new Store();
String orderOfString = obj1.CheckOrder(input);
System.out.println(orderOfString);
HashMap inputLocation = obj1.getCharacterLocation(input);
HashMap input1Location = obj1.getCharacterLocation(input1);
System.out.println(inputLocation);
System.out.println(input1Location);
HashMap input1Location = obj1.getCharacterLocation(input1);
// This is the comparison of the value from the key
inputLocation.get(inputLocation.keySet()[2]).equals(input1Location.get(input1Location.keySet()[2]);
// 2 is the second argument of the key value in the HashMap
// This is the comparison of the two hashes
inputLocation.equals(input1Location);
// OUTPUT of print
// inputLocation = {0=72, 1=101, 2=108, 3=108, 4=111}
// input1Location = {0=101, 1=72, 2=108, 3=108, 4=111}
// true
// false
}}
如果需要的是已更改的值的计数,则此代码应该可以工作
HashMap inputLocation = obj1.getCharacterLocation(input);
HashMap input1Location = obj1.getCharacterLocation(input1);
int diffCount = 0;
for (Object key : inputLocation.keySet()) {
if ( !inputLocation.get(key).equals(input1Location.get(key))){
diffCount++;
}
}
diffCount将为您提供更改值的计数
这只是一些粗略的代码,请随时更新。我建议您使用
HashMap
而不是普通的HashMap
,因为这样可以保证类型安全。对于您的特定情况,如何循环键并将它们添加到一个新的HashMap中?比如result.put(key,inputLocation.get(key)-input1Location.get(key))
@BlackPearl你能把它作为一个完整的答案吗?看起来没问题……我好像误解了这个问题。您能否提供所需的样本输出?输出是以映射的形式吗?我在示例
下的问题中以整数的形式提供了输出。在这里,72和101的键都已更改。有什么理由只检查72吗?你能提供一个更完整的代码片段吗?我重新表述了答案这引发了一个错误:(方法get(int)对于类型集是未定义的
尝试更改为get(2),改为[2]什么是abcd.keySet()
我需要在某个地方定义它吗?@PhilkeySet
是Map
的标准方法,请参阅。