简体   繁体   中英

What is the best way to compare values in two Properties objects?

I have two Properties instances which contain same keys but may contain different values(strings). What is the best way to check if the values are identical in both the instances.

Right now I am using if conditions to check like below

if(!p1.getProperty("x").equals(p2.getProperty("x")) {
    return true;
}

Properties is a subclass of HashTable , which overrides equals . You can simply compare the instances using equals :

properties1.equals(properties2)

But this won't tell you what is different.

To do that, you can get the keys using properties.keySet() , and then compare the values between the two instances:

for (String key : properties1.keySet()) {
  String value1 = properties1.get(key);
  String value2 = properties2.get(key);

  // Compare, e.g. value1.equals(value2).
  // But may need to take into account missing values.
}

Note that this is asymmetrical, in the sense that it looks for the values for which values exist in properties1 . If you want to search for the intersection (or union) of the keys, just build that set first:

Set<String> keys = new HashSet<>(properties1.keySet());
// For intersection:
keys.retainAll(properties2.keySet());
// For union:
// keys.addAll(properties2.keySet());

for (String key : keys) { ... }
String value=p1.getProperty("x");
if (value == null) {
                    if (!(p2.getProperty("x")==null && p2.containsKey("x")))
                        return true;
} else {
                    if (!value.equals(p2.getProperty("x")))
                        return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM