如何通过Java中的嵌套HashMap创建值的数组列表?

我已经使用嵌套的HashMap编写了代码,并且试图找出如何将内部映射键所指向的所有值都放入ArrayList中,以便对其进行正确排序。 我的地图看起来像这样:

HashMap<String,HashMap<String,Double>> vlist;

我的想法是创建另一个HashMap,使其具有与之前显示的内部映射相同的键和值, 然后以这种方式填充它。

HashMap<String,Double> vlistvalues = new HashMap<>(vlist.values());

我得到一个编译错误,我可以发现编译器不知道我的外部映射的值就是一个映射本身,但是在阅读哈希映射文档时,我没有找到适合我情况的方法。

基本上我想将此处声明的内部映射的所有值HashMap<String,Double>> vlist;放入这样的列表ArrayList<Double> listOfValues;

如果不清楚,我是编程新手:-)

我将显示一个示例: 我的地图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循环中对边进行排序。可能我的代码效率不高,但是我真的不知道如何在不访问所有图形的情况下对边缘进行排序。附言:我不能使用优先级队列,但我完全知道我要做的事情类似

love990311 回答:如何通过Java中的嵌套HashMap创建值的数组列表?

所以你说:

基本上,我想将此处声明的内部映射的所有值放在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);

这是地图。

  

{Z = {P = 22.3},B = {S = 9.8,V = 2.8},A = {T = 3.8,S = 3.4,R = 1.2}}

要转换为List的两倍,您可以执行此操作。获取stream中的values(它们是内部映射),然后通过combine all the values in those mapsflatMap转换为公共流,然后收集到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的{​​{1}}中创建一个entrySet,并将其传递到outer mapcollector使用collector创建一个映射,然后获取outer maps key(它是一个集合)的值,并将它们作为参数传递给inner map,以创建一个{ {1}}。

ArrayList<>

这是地图。

  

{A = [1.2,3.4,3.8],B = [2.8,9.8],Z = [22.3]}

,

在像HashMap<String,Double>> vlist;这样的地图上

  • vlist.keys()List<String>,其中包含所有键
  • vlist.values()List<HashMap<String,Double>>,其中包含所有作为值的地图

要获取特定的List<Double>,您需要一把钥匙,因此请选择您要从中读取双打的内部地图

HashMap<String,Double>> outer = ...; // don't call a map *list*
HashMap<String,Double> inner  = outer.get("mykey");
List<Double> values = new ArrayList<>(inner.values()); // as values() returns a Collection
本文链接:https://www.f2er.com/2955771.html

大家都在问