如何比较两个Hashmaps

时间:2015-08-11 12:08:12

标签: java

我在这里填写了两个Hashmaps:

private String[] tabs = { "Top Rated", "Games", "Movies" };
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Initilization
    viewPager = (ViewPager) findViewById(R.id.pager);
    actionBar = getActionBar();
    mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

    viewPager.setAdapter(mAdapter);
    actionBar.setHomeButtonEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);        

    // Adding Tabs
    for (String tab_name : tabs) {
        actionBar.addTab(actionBar.newTab().setText(tab_name)
                .setTabListener(this));
    }

声明:

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());
}
他们看起来像是:

enter image description here

如果public Map<String,String> compareMap = new HashMap<>(); public Map<String, String> xmlFileMap = new HashMap<>(); 变为空,我怎样才能检查它是否为空? 有时job_id并不存在。因此,job_id中缺少{。}}。

有时在job_id中有一个compareMap

如何比较job_id&并且在比较时获得job_id值?

1 个答案:

答案 0 :(得分:3)

似乎您想根据特定模式查找地图密钥。这可以通过迭代所有键来完成:

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;
}

如果您可能有多个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;
}

现在您可以使用此方法来比较不同地图的job_id:

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