Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a set of values from a map

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?

like image 512
Sanjana Avatar asked Sep 29 '13 06:09

Sanjana


People also ask

How do you return a value from a map?

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.

What does map values () return in Java?

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.

What is map return type?

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.)


2 Answers

Just create a new HashSet with map.values()

public Set<Employee> listAllEmployees()
{
      return  new HashSet<Employee>(map.values());                
}
like image 151
Suresh Atta Avatar answered Oct 14 '22 05:10

Suresh Atta


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

like image 27
Oleg Ushakov Avatar answered Oct 14 '22 04:10

Oleg Ushakov