我想将HashMap转换为Set.I我试图通过首先将它放到一个集合并使用retainAll来找到两个映射之间的公共元素。如何将地图转换为集合。
答案 0 :(得分:3)
根据您希望提取的内容,您可以查看这三种方法之一(Java 7):
Collection
,而不是Set
,但这应该更容易转换。答案 1 :(得分:0)
也许你需要的只是 https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#entrySet-- 要么 https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#keySet--
如您所见,调用map.values()
或map.keySet()
会返回包含所有值或键的集合。
答案 2 :(得分:0)
要查找两个地图的交集,使用java.util.Set.retainAll()
是合理的,但最终设置的是Set<Map.Entry>
。如果想再次使用这些条目,必须重新映射它们(如下例所示)。
在下面的示例中,两行完成所有工作。该示例分为三个部分:
显示结果。
public static void main(String[] args) {
// **** Section 1: Setup ****
// Create 3 maps; Two with duplicate values
// and a third to hold the ultimate results
Map<String, String> m2 = new HashMap<String, String>();
Map<String, String> m1 = new HashMap<String, String>();
Map<String, String> common = new HashMap<String, String>();
// Populate test map 1
m1.put("1", "One");
m1.put("2", "Two");
m1.put("2a", "Two");
// Create map 2 containing some of the same values in map 1
m2.put("I", "One");
m2.put("1", "One");
m2.put("II", "Two");
m2.put("2", "Two");
// **** Section 2: Perform the intersection ****
// create a set to handle the intersection
Set<Map.Entry<String,String>> dups = m1.entrySet();
dups.retainAll(m2.entrySet());
// Remap the results that were common to both maps
for (Map.Entry<String, String> entry: dups) {
common.put(entry.getKey(), entry.getValue());
}
// **** Section 3: Show the results ****
// show the resulting map of values found in both maps
int ii = 0;
for (Map.Entry<String, String> entry: dups) {
System.out.println("Common member " + ++ii + "= " + entry.getKey() + ":" + entry.getValue());
}
// show the original maps
showMap(1, m1);
showMap(2, m2);
}
static private void showMap(int mapNumber, Map<String,String> m) {
int ii = 0;
for (Map.Entry<String, String> entry: m.entrySet()) {
System.out.println("Map " + mapNumber
+ " member " + ++ii
+ ": key = " + entry.getKey()
+ ": value = " + entry.getValue());
}
}