1

I have a small query with respect to the comparison of ArrayList value with the HashMap value and extract the key value if they are equal. I am reading two files and storing them in ArrayList and HashMap respectively. I have to compare these values and extract the key from HashMap.

For example:

ArrayList<String> list=new ArrayList<String>();
list.add("A");
list.add("B");  
list.add("C");  
list.add("D");  
Iterator itr=list.iterator();  
while(itr.hasNext()){  
    System.out.println(itr.next());  
}

HashMap<String,String> hm=new HashMap<String,String>();  
hm.put("Key A","A");  
hm.put("Key B","B");  
hm.put("Key C","C");  
hm.put("Key D","D");  
for(Map.Entry m : hm.entrySet()){  
    System.out.println(m.getKey() + " " + m.getValue());  
}

I have to compare the ArrayList and HashMap and if both of them contains the value "A" then Key A should be returned.

2
  • 1
    Start by looking how can you find if a list contains an item, continue by checking how to get the values of a hashmap and see if they contain the item as well, and if both answers returned as "true" then you can iterate the entries of the hashmap looking for the key who's value is the requested item. Good luck! Commented Feb 7, 2017 at 20:07
  • 1
    I strongly suggest that you'll ignore the answers and try to implement it by yourself. True, it will take more time - but that's exactly how you'll learn. And next time it will be much easier! Commented Feb 7, 2017 at 20:10

2 Answers 2

3

As an alternative to bc004346's answer, you can also solve this puzzle in a functional style using Streams:

List<String> result = hm.entrySet().stream()
    .filter(entry -> list.contains(entry.getValue()))
    .map(entry -> entry.getKey())
    .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

2

Just iterate over you HashMap and see if a value matches a value from ArrayList

    HashMap<String,String> hm=new HashMap<String,String>();
    hm.put("Key A","A");
    hm.put("Key B","B");
    hm.put("Key C","C");
    hm.put("Key D","D");
    for(Map.Entry m : hm.entrySet()){
        if (list.contains(m.getValue()))
            System.out.println("Bingo: " + m.getKey());
    }

1 Comment

Code only answers are not appropriate for Stack Overflow. Please add an explanation to your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.