简体   繁体   English

如何比较两个Hashmaps

[英]How to compare two Hashmaps

I have two Hashmaps filled here: 我在这里填写了两个Hashmaps:

Properties properties = new Properties();
try {
    properties.load(openFileInput("xmlfilesnames.xml"));
} catch (IOException e) {
    e.printStackTrace();
}
for (String key : properties.stringPropertyNames()) {
    xmlFileMap.put(key, properties.get(key).toString());
}

try {
    properties.load(openFileInput("comparexml.xml"));
} catch (IOException e) {
    e.printStackTrace();
}
for (String key : properties.stringPropertyNames()) {
    compareMap.put(key, properties.get(key).toString());
}

Declaration: 宣言:

public Map<String,String> compareMap = new HashMap<>();
public Map<String, String> xmlFileMap = new HashMap<>();

they look like: 他们看着像是:

在此输入图像描述

How can I check if the job_id changed of maybe if it's null? 如何检查job_id是否为null? Sometimes the job_id doesn't really exists. 有时job_id确实不存在。 So the job_id is missing in them. 因此,缺少job_id

And Sometimes in compareMap are more then one job_id 有时在compareMap中有一个job_id

How can I compare just the job_id 's and get a boolean value when compared? 我如何只比较job_id并在比较时得到一个boolean值?

Seems that you want to find the map key based on specific pattern. 似乎您想要根据特定模式查找地图密钥。 This can be done by iterating over all keys: 这可以通过迭代所有键来完成:

private static String PREFIX = "<job_id>";
private static String SUFFIX = "</job_id>";

public static String extractJobId(Map<String, ?> map) {
    for(String key : map.keySet()) {
        if(key.startsWith(PREFIX) && key.endsWith(SUFFIX))
            return key.substring(PREFIX.length(), key.length()-SUFFIX.length());
    }
    // no job_id found
    return null;
}

If you may have several job_id keys and want to check whether all of them are the same, you can build an intermediate set instead: 如果您可能有多个job_id键并想要检查它们是否全部相同,则可以构建一个中间集:

public static Set<String> extractJobIds(Map<String, ?> map) {
    Set<String> result = new HashSet<>();
    for(String key : map.keySet()) {
        if(key.startsWith(PREFIX) && key.endsWith(SUFFIX))
            result.add(key.substring(PREFIX.length(), key.length()-SUFFIX.length()));
    }
    return result;
}

Now you can use this method to compare job_id of different maps: 现在您可以使用此方法来比较不同地图的job_id:

if(Objects.equals(extractJobIds(xmlFileMap), extractJobIds(compareMap))) {
    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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