Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 extract all keys from matching values in a Map

I'm relatively new to Java8 and I have a scenario where I need to retrieve all the keys from the Map which matched with the objects.

Wanted to know if there is a way to get all keys without iterating them from the list again.

Person.java
private String firstName;
private String lastName;
//setters and getters & constructor


MAIN Class.

String inputCriteriaFirstName = "john";   

Map<String, Person> inputMap = new HashMap<>();
Collection<Person> personCollection = inputMap.values();
List<Person> personList = new ArrayList<>(personCollection);
List<Person> personOutputList = personList.stream()
.filter(p -> p.getFirstName().contains(inputCriteriaFirstName ))
.collect(Collectors.toList());


//IS There a BETTER way to DO Below ??

Set<String> keys = new HashSet<>();
for(Person person : personOutputList) {
    keys.addAll(inputMap.entrySet().stream().filter(entry -> Objects.equals(entry.getValue(), person))
        .map(Map.Entry::getKey).collect(Collectors.toSet()));
}
like image 645
Srinivas Lakshman Avatar asked Mar 16 '18 21:03

Srinivas Lakshman


People also ask

How do I get a list of keys on a Map?

To retrieve the set of keys from HashMap, use the keyset() method. However, for set of values, use the values() method.

Can we get key from value in Map Java?

Get keys from value in HashMap To find all the keys that map to a certain value, we can loop the entrySet() and Objects. equals to compare the value and get the key. The common mistake is use the entry. getValue().


1 Answers

inputMap.entrySet() 
        .stream()
        .filter(entry -> personOutputList.contains(entry.getValue()))
        .map(Entry::getKey)
        .collect(Collectors.toCollection(HashSet::new))
like image 182
Eugene Avatar answered Oct 10 '22 05:10

Eugene