java 从地图中获取条目集

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7477480/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:09:27  来源:igfitidea点击:

Get Set of entries from a Map

javacollectionsmap

提问by john

Given a map such as:

给定一张地图,例如:

Map<String, Integer> = new Hashmap<String, Integer>;

How can I get a Collection<Integer>(any implementation of Collection would do) of the entrySet? Doing .entrySet()doesn't seem to work.

如何获得Collection<Integer>entrySet的(Collection 的任何实现都可以)?这样.entrySet()做似乎不起作用。

回答by hvgotcodes

If you want to get just the map values you can use the values()method. The Javadoc page is here.

如果您只想获取地图值,则可以使用该values()方法。Javadoc 页面在这里

This is because your requirement is a Collection of Integers and the map values are of Integer type.

这是因为您的要求是整数集合,并且地图值是整数类型。

entrySetreturns a collection of Map.Entry, each instance of which contains both the key and value that make up the entry, so if you want both the key and value, use entrySet()like so

entrySet返回 的集合Map.Entry,其中的每个实例都包含构成条目的键和值,因此如果您需要键和值,请entrySet()像这样使用

Set<Map.Entry<String, Integer>> entries = map.entrySet()

Set<Map.Entry<String, Integer>> entries = map.entrySet()

回答by John B

That depends on if you truly want a SET. If you want a true Set you must do:

这取决于你是否真的想要一个 SET。如果你想要一个真正的 Set 你必须这样做:

Set mySet = new HashSet(map.values());

Notice that valuesgives a Collection which can have duplicate entries.

请注意,values给出了一个可能有重复条目的集合。