简体   繁体   中英

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?

Just create a new HashSet with map.values()

public Set<Employee> listAllEmployees()
{
      return  new HashSet<Employee>(map.values());                
}

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.

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

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