I have a map HashMap <Integer,Employee> map= new HashMap<Integer,Employee>();
The class Employee
has an int attribute int 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?
The get() method of Map interface in Java is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
Map Values() method returns the Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa.
Returns: the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key, if the implementation supports null values.)
Just create a new HashSet
with map.values()
public Set<Employee> listAllEmployees()
{
return new HashSet<Employee>(map.values());
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With