How to compare two hashmaps

I have two Hashmaps filled here:

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 this:

enter image description here

How can I check if job_id has changed, possibly if it is zero? Sometimes job_id does not really exist. So job_id missing from them.

And sometimes compareMap more than one job_id

How to compare only job_id and get boolean value when comparing?

+4
source share
1 answer

It seems that you want to find a card key based on a specific pattern. This can be done by iterating over all the 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 can have multiple job_id keys and want to check if they are all the same, you can create an intermediate set instead:

 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 cards:

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

All Articles