Return a set of values from a map
20,152
Solution 1
Just create a new HashSet
with map.values()
public Set<Employee> listAllEmployees()
{
return new HashSet<Employee>(map.values());
}
Solution 2
In Java 8 by Stream API you can use this method
public Set<Employee> listAllEmployees(Map<Integer,Employee> map){
return map.entrySet().stream()
.flatMap(e -> e.getValue().stream())
.collect(Collectors.toSet());
}
Upd.: This code performs the task but is some kind of overcoding. Just KISS and do it as in answer here https://stackoverflow.com/a/19075053/4609353
Solution 3
Some other options.
You can still use the Collection Interface to do all possible set operations. Iteration, clear etc etc. (Note that the Collection returned by values() is an unmodifiable collection)
Use map.values().toArray() method and return an array.
Author by
Sanjana
Updated on July 09, 2022Comments
-
Sanjana almost 2 years
I have a map
HashMap <Integer,Employee> map= new HashMap<Integer,Employee>();
The classEmployee
has an int attributeint empid;
which will serve as key to the map.My method is
public Set<Employee> listAllEmployees() { return map.values(); //This returns a collection,I need a set }
How to get set of employees from this method?