Java 从地图返回一组值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19075027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return a set of values from a map
提问by Sanjana
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.
我有一个地图HashMap <Integer,Employee> map= new HashMap<Integer,Employee>();
类Employee
有一个 int 属性int empid;
,它将作为地图的关键。
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?
如何从这种方法中获取一组员工?
采纳答案by Suresh Atta
Just create a new HashSet
with map.values()
只需创建一个新HashSet
的map.values()
public Set<Employee> listAllEmployees()
{
return new HashSet<Employee>(map.values());
}
回答by anuu_online
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)
您仍然可以使用集合接口来执行所有可能的设置操作。迭代、清除等(注意 values() 返回的 Collection 是一个不可修改的集合)
Use map.values().toArray() method and return an array.
使用 map.values().toArray() 方法并返回一个数组。
回答by Oleg Ushakov
In Java 8 by Stream API you can use this method
在 Java 8 by Stream API 中,您可以使用此方法
public Set<Employee> listAllEmployees(Map<Integer,Employee> map){
return map.entrySet().stream()
.flatMap(e -> e.getValue().stream())
.collect(Collectors.toSet());
}