Java:将HashMap值转换为Set<;整数>;

Java:将HashMap值转换为Set<;整数>;,java,hashmap,set,Java,Hashmap,Set,关于Java中的HashMap还有一个问题: 我有以下几点 Map<String, Set<Integer>> myWordDict = new HashMap<String, Set<Integer>>(); Map myWordDict=newhashmap(); 在将数据存储到变量myWordDict中之后,我想迭代HashMapValues,并将每个值添加到一个新的Set变量中 当我尝试设置newVariable=myWordDict.

关于Java中的HashMap还有一个问题:

我有以下几点

Map<String, Set<Integer>> myWordDict = new HashMap<String, Set<Integer>>();
Map myWordDict=newhashmap();
在将数据存储到变量
myWordDict
中之后,我想迭代HashMapValues,并将每个值添加到一个新的Set变量中

当我尝试设置newVariable=myWordDict.entrySet()时,数据类型似乎不兼容

所以我的问题基本上是:

如何将HashMap值或entrySet()转换为Set


谢谢使用
myWordDict.values()
,而不是
myWordDict.entrySet()
。values是映射的
值的集合,而
entrySet
是映射的集合(它是一组java.util.map.Entry对象,每个对象描述一个键和一个值)。

您的声明应该如下所示。它会将地图值转换为
集合

  Collection<Set<Integer>> newVariable = myWordDict.values();
Collection newVariable=myWordDict.values();

如果您需要所有值作为
整数的
集合,而不是
集合的
集合,那么您可以这样做

Set<Integer> newVariable = new HashSet<Integer>();
for (Set<Integer> set : myWordDict.values()) {
    newVariable.addAll(set);
}
Set<Set<Integer>> newVariable = new HashSet<Set<Integer>>();
newVariable.addAll(myWordDict.values());
Map map1=newhashmap();
map1.put(1,“Rakesh”);
map1.put(2,“Amal”);
map1.put(3,“Nithish”);
Set set1=map1.entrySet();

相关链接

试试:

Set<Integer> newVariable = mywordDict.keySet();
Set newVariable=mywordDict.keySet();

Set newVariable=newhashset(myWordDict.values());

假设您要添加地图中集合的所有值,您的方法是使用以下方法:

Set<Integer> newVariable = new HashSet<Integer>();
for (Set<Integer> set : myWordDict.values()) {
    newVariable.addAll(set);
}
Set newVariable=newhashset();
for(Set:myWordDict.values()){
newVariable.addAll(set);
}

因此,我想出了一个迭代器来迭代值集

我有这个数据结构

Map<String, Set<Integer>> myWordDict = new HashMap<String, Set<Integer>>();
然后使用while()循环将单个值添加到新的集合变量。我不确定这是最有效的方法,但它适合我的需要。`

flatMap将帮助您:

myWordDict.values().stream().flatMap(Set::stream).collect(Collectors.toSet());

映射值类型是什么?是否要将所有键值组合作为一组?或者您只需要键或值?我只希望集合中有值。值类型为整数。@TonyGW您说值类型为整数,但在上面的示例中,值类型实际上已设置。是的,值已设置。很抱歉,confusionvalues()属于集合类型,因此除非我执行难看的强制转换,否则还存在数据不兼容问题。@TonyGW AFAIK没有办法解决这个问题,除非您希望通过添加条目集中的每个值来手动构造集合。我现在使用迭代器迭代HashMap值:您确定这会起作用吗?!首先,您必须强制转换它,即使您这样做,它也会抛出一个
ClassCastException
@TonyGW,它根据
myWordDict
中的条目数运行-如果您有10个条目,
for
循环将进行10次迭代。
Set<Integer> newVariable = new HashSet<Integer>(myWordDict.values());
Set<Integer> newVariable = new HashSet<Integer>();
for (Set<Integer> set : myWordDict.values()) {
    newVariable.addAll(set);
}
Map<String, Set<Integer>> myWordDict = new HashMap<String, Set<Integer>>();
Iterator mapIterator = myWordDict.entrySet().iterator();
myWordDict.values().stream().flatMap(Set::stream).collect(Collectors.toSet());