如何检查两个属性对象是否在java中重叠?

时间:2017-02-27 09:09:48

标签: java properties

我有两个属性property1property2

 Properties properties1 = new Properties();
 Properties properties2 = new Properties();

 properties1.put("A", "Apple");
 properties1.put("B", "Ball");

 properties2.put("A", "Apple");
 properties2.put("C", "Cat");

我们如何检查properties1中的密钥是否与properties2中的密钥重叠

6 个答案:

答案 0 :(得分:2)

属性来自HashTable,因此来自Map

与Map一样,您可以使用properties1.entrySet()来迭代所有条目和 然后,对于每个条目,您可以通过首先查看密钥是否包含以及是否包含密钥来检查它是否包含在properties2中,您可以比较这些值:

    for (Entry<Object, Object> entry : properties1.entrySet()) {
        Object currentKey = entry.getKey();
        boolean isContained = properties2.containsKey(currentKey);
        if (isContained && entry.getValue().equals(properties2.get(currentKey))) {
            System.out.println("property equals for " + entry);
        }
    }

答案 1 :(得分:2)

您可以查找两个属性名称集的交集,然后检查哪些值不同:

Set<String> names1 = properties1.stringPropertyNames();
Set<String> names2 = properties2.stringPropertyNames();
names1.retainAll(names2); // after this line, names1 contains only common elements

// let's see which elements have different values
for(String str : names1){
    if(!properties1.getProperty(str).equals(properties2.getProperty(str))){
        System.out.println("Property "+str+" overlapping");
    }
}

答案 2 :(得分:1)

Properties扩展Hashtable,因此您可以使用set intersection找到两个对象中存在的键:

Set<Object> intersection = new HashSet(properties1.keySet()).retainAll(properties2.keySet());
if(intersection.isEmpty()) {
    //no overlap
}

答案 3 :(得分:1)

例如,使用Java 8:

    // Returns overlapping entries (K, V)
    properties1.entrySet()
               .stream()
               .filter(entry -> entry.getValue().equals(properties2.get(entry.getKey())))
               .collect(Collectors.toList())
    );

答案 4 :(得分:1)

您可以查看两个Set<Entry<Object, Object>> intersection = new HashSet<>(properties1.entrySet()); intersection.retainAll(properties2.entrySet()); 对象条目集之间的交集:

intersection

Node将包含具有键名和值的公共属性。

答案 5 :(得分:0)

您可以对所有条目进行迭代(使用entrySet()方法)并检查它们是否存在于其他属性中。

boolean overlapped = properties1.entrySet()
                                .stream()
                                .allMatch(e -> properties2.containsKey(e.getKey()) && 
                                     properties2.get(e.getKey()).equals(e.getValue()));