简体   繁体   中英

Compare the ArrayList values and HashMap values

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.

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

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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