我已经使用嵌套的 HashMap 编写了代码,我正在尝试弄清楚如何将内部映射的键指向的所有值放入 ArrayList 中,以便对其进行正确排序。 我的 map 如下所示:
HashMap<String, HashMap<String, Double>> vlist;
我的想法是创建另一个 HashMap,其键和值与之前显示的内部映射相同, 然后以这种方式填充它。
HashMap<String, Double> vlistValues = new HashMap<>(vlist.values());
我收到编译错误,我可以发现编译器不知道我的外部映射的值是映射本身,但是阅读 hashmap 文档我没有找到适合我的情况的方法。
基本上我想把这里声明的内部映射的所有值HashMap<String ,HashMap<String, Double>> vlist;
到这样的列表 ArrayList<Double> listOfValues;
如果不清楚的话,我对编程完全陌生:-)
我将展示一个例子:
我的 map HashMap<String, Hashmap<String,Double>>
表示加权图的邻接表。我需要对所有边进行排序(因为我正在尝试实现 Kruskal 算法),我的想法是将所有权重放在一个列表中,执行如下操作:
ArrayList<String> vertexList; //all the vertices of the graph
ArrayList<Double> weights;
HashMap<String, String> orderedEdges = new HashMap<>(); //here i put ordered edges
double min = Collections.min(weights); //i use this double to keep track of the minimum element in weights
for(String vertex1 : vertexlist){
makeSet(vertex1);
for(String vertex2 : ajacents(vertex1)){
if(getEdgeWeight(v1,v2) <= min){ //method "getEdgeWeight" is to retrieve weight of an edge
orderedEdges.put(v1,v2);
min = getEdgeWeight(v1,v2)
weights.remove(min) //i'm not sure this line is correct
}
}
}
在网上查看一些伪代码,我发现它能够在同一个 for 循环中创建不相交的集合并对边进行排序。也许我的代码效率不高,但我真的不知道如何在不访问所有图表的情况下对边缘进行排序。 PS我不能使用优先级队列,但我完全知道我想做的是类似的事情
最佳答案
所以你说:
基本上我想把这里声明的内部映射的所有值HashMap<String ,HashMap<String, Double>> vlist
;到这样的列表 ArrayList<Double> listOfValues
这是示例 hashMap。
Map<String, Map<String, Double>> mm = Map.of("A",
Map.of("R", 1.2, "S", 3.4, "T", 3.8),
"B",
Map.of("S", 9.8, "V", 2.8),
"Z",
Map.of("P", 22.3));
System.out.println(mm);
这是 map 。
{Z={P=22.3}, B={S=9.8, V=2.8}, A={T=3.8, S=3.4, R=1.2}}
转换为List
double 你可以做到这一点。获取stream
values
的(这是内部 map ),然后 combine all the values in those maps
通过 flatMap
进入公共(public)流然后收集到List
.
List<Double> dubs =
mm.values().stream().flatMap(k -> k.values().stream()).collect(
Collectors.toList());
System.out.println(dubs);
这是列表。
[22.3, 9.8, 2.8, 3.8, 3.4, 1.2]
如果你想要 Map<String, List<Doubles>>
其中 String 是外部 Map 的键,您可以执行此操作。创建 stream
的entrySet
outer map
的并将其传递给 collector
。 collector
使用 outer maps key
创建 map 然后取 inner map
的值(这是一个集合)并将它们作为参数传递给 ArrayList<>
创建 List
.
Map<String, List<Double>> mapOfDubs =
mm.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(),
e -> new ArrayList<>(e.getValue().values())));
System.out.println(mapOfDubs);
这是 map 。
{A=[1.2, 3.4, 3.8], B=[2.8, 9.8], Z=[22.3]}
关于java - 如何从 java 中的嵌套 HashMap 创建值的数组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59231013/