简体   繁体   English

从哈希图中检索多个值

[英]Retrieving Multiple values from hashmap

Data Class contains two fields price (double), operator (string), I mapped the Data class as multiple values to each key of the map shown below as 1). 数据类包含两个字段价格(双精度),运算符(字符串),我将数据类作为多个值映射到映射的每个键,如下所示(1)。

I am unable to show in the the code 2). 我无法在代码2中显示。 all the values that are mapped under the same key, 在同一个键下映射的所有值,

Example, for Key=1, map has Values as Price {0.2,0.3,0.4} , Operator: {A,B,C} 例如,对于键= 1,地图的值为:价格{0.2,0.3,0.4},运算符:{A,B,C}

the output of this code, can only show me price= 0.2, Operator: A for Key 1. all other values are not shown. 此代码的输出只能向我显示price = 0.2,操作员:键1的A。未显示所有其他值。 how to solve it? 怎么解决呢?

1) Map<Integer, ArrayList<Data>> mp = new HashMap<Integer, ArrayList <SortData>>();

2) 2)

       ArrayList<Data> ls = mp.get (keys.get(k));

              int i=0;
            for ( Data e: ls)
            {           
     System.out.println(e.getOperator() + e.getPrice());
                i++;    
            }

Code of Adding Data in the Map: 在地图中添加数据的代码:

enter code here
     ArrayList<Test> list = new ArrayList<Test>();
      Map<Integer,ArrayList<Test>> mp = new HashMap<Integer,ArrayList<Test>>();
       list.add(new Data(0,1,"A"));
    list.add(new Data(0,2,"B"));
     mp.put(1,list);

  List<Test> value = mp.get(1);
  value.add(0.3,"c");
  value.add(0,5,"E");

In your code for adding values to the map - Compilation error. 在将值添加到地图的代码中-编译错误。 You cannot add Data objects to ArrayList. 您不能将数据对象添加到ArrayList。

Your iteration code is correct. 您的迭代代码是正确的。 So I believe the values simply doesn't exists in the Map. 因此,我认为地图中根本就不存在这些值。 So review all code remove values from the list. 因此,请查看所有代码,从列表中删除值。 And be sure in your add values code you add values to the same instance stored in the Map. 并确保在添加值代码中将值添加到存储在地图中的同一实例中。

Nevertheless to create less errorphone code consider using Guava MultiMap 不过,要创建更少的错误电话代码,请考虑使用Guava MultiMap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM