Reputation: 915
The code below does not work. What logic can I use to print the key Job which has 2 different values in 2 hash maps?
public void randomTest() throws IOException {
HashMap<String, String> map1 = new HashMap<>();
HashMap<String, String> map2 = new HashMap<>();
map1.put("Name", "Jones");
map1.put("Job", "QAE");
map2.put("Name", "Jones");
map2.put("Job", "Developer");
// ArrayList<String> ar = new ArrayList<>();
Set<String> hs = new HashSet<>();
for (Map.Entry<String, String> mm1 : map1.entrySet()) {
hs.add(mm1.getValue());
}
for (Map.Entry<String, String> mm2 : map1.entrySet()) {
hs.add(mm2.getValue());
}
for(String s: hs){
System.out.println(s);
}
/* for (Map.Entry<String, String> mm1 : map1.entrySet()) {
for(String str: hs){
if(str.equals(mm1.getValue())){
System.out.println(mm1.getKey());
}
}
}*/
}
Expected output: Job.
Thanks in advance for your time.
Upvotes: 0
Views: 1156
Reputation: 86343
This logic does the job (no pun intended).
HashMap<String, String> map1 = new HashMap<>();
HashMap<String, String> map2 = new HashMap<>();
map1.put("Name", "Jones");
map1.put("Job", "QAE");
map2.put("Name", "Jones");
map2.put("Job", "Developer");
Set<String> hs = new HashSet<>();
for (Map.Entry<String, String> mm1 : map1.entrySet()) {
String map2Value = map2.get(mm1.getKey());
if (! Objects.equals(mm1.getValue(), map2Value)) {
hs.add(mm1.getKey());
}
}
for(String s: hs){
System.out.println(s);
}
Output:
Job
I have added a comparison of the values from the two maps. Furthermore I am doing hs.add(mm1.getKey());
instead of hs.add(mm1.getValue());
to have the non-matching key/s printed.
It’s also a nice case for applying a stream operation if you like. If so, use the code from the answer by Oboe.
The code assumes that the keys are the same in both maps. You should probably check this assumption and issue a message if it doesn’t hold.
Upvotes: 1
Reputation: 2723
Try these:
map1.entrySet().stream()
.filter(entry -> map2.get(entry.getKey()) != null)
.filter(entry -> !map2.get(entry.getKey()).equals(entry.getValue()))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
Upvotes: 1
Reputation: 40218
Here's what you can do:
Set
.Set
, query values from both maps.Upvotes: 1