从hashmap存储和检索ArrayList值

时间:2013-10-23 12:23:36

标签: java arraylist hashmap

我有以下类型的散列图

HashMap<String,ArrayList<Integer>> map=new HashMap<String,ArrayList<Integer>>();    

存储的值如下:

mango | 0,4,8,9,12
apple | 2,3
grapes| 1,7
peach | 5,6,11

我想存储以及使用Iterator或任何其他方式使用最少的代码行获取这些整数。我该怎么办?

编辑1

随着密钥与相应的行匹配,数字会随机添加(不在一起)。

编辑2

添加时如何指向arraylist?

我在行18

中添加新号码map.put(string,number);时收到错误

7 个答案:

答案 0 :(得分:35)

我们的变量:

Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();

存储:

map.put("mango", new ArrayList<Integer>(Arrays.asList(0, 4, 8, 9, 12)));

要添加数字1和1,您可以执行以下操作:

String key = "mango";
int number = 42;
if (map.get(key) == null) {
    map.put(key, new ArrayList<Integer>());
}
map.get(key).add(number);

在Java 8中,如果列表已经不存在,您可以使用putIfAbsent添加列表:

map.putIfAbsent(key, new ArrayList<Integer>());
map.get(key).add(number);

使用map.entrySet()方法进行迭代:

for (Entry<String, List<Integer>> ee : map.entrySet()) {
    String key = ee.getKey();
    List<Integer> values = ee.getValue();
    // TODO: Do something.
}

答案 1 :(得分:2)

您可以这样使用(虽然随机数生成器逻辑不符合标记)

public class WorkSheet {
    HashMap<String,ArrayList<Integer>> map = new HashMap<String,ArrayList<Integer>>();

public static void main(String args[]) {
    WorkSheet test = new WorkSheet();
    test.inputData("mango", 5);
    test.inputData("apple", 2);
    test.inputData("grapes", 2);
    test.inputData("peach", 3);
    test.displayData();

}
public void displayData(){
    for (Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
        System.out.print(entry.getKey()+" | ");
        for(int fruitNo : entry.getValue()){
            System.out.print(fruitNo+" ");
        }
        System.out.println();
    }
}
public void inputData(String name ,int number) {
    Random rndData = new Random();
    ArrayList<Integer> fruit = new ArrayList<Integer>();
    for(int i=0 ; i<number ; i++){
        fruit.add(rndData.nextInt(10));
    }
    map.put(name, fruit);
}
}

输出

grapes | 7 5 
apple | 9 5 
peach | 5 5 8 
mango | 4 7 1 5 5 

答案 2 :(得分:1)

Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
     Map.Entry pairs = (Map.Entry)it.next();

     if(pairs.getKey().equals("mango"))
     {
        map.put(pairs.getKey(), pairs.getValue().add(18));
     }

     else if(!map.containsKey("mango"))
     {
        List<Integer> ints = new ArrayList<Integer>();
        ints.add(18);
        map.put("mango",ints);
     }

     it.remove(); // avoids a ConcurrentModificationException
}

编辑: 所以在里面试试这个:

map.put(pairs.getKey(), pairs.getValue().add(number))

您收到错误是因为您尝试将整数放入值中,而预期值为ArrayList

编辑2: 然后将以下内容放入while循环中:

if(pairs.getKey().equals("mango"))
{
    map.put(pairs.getKey(), pairs.getValue().add(18));
}

else if(!map.containsKey("mango"))
{
     List<Integer> ints = new ArrayList<Integer>();
     ints.add(18);
     map.put("mango",ints);
 }

编辑3: 通过阅读您的要求,我认为您可能不需要循环。您可能只想检查地图是否包含密钥mango,以及是否添加18,否则在地图中使用密钥mango和值{{1}创建新条目}。

所以你可能需要的是以下内容,没有循环:

18

答案 3 :(得分:0)

for (Map.Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
 System.out.println( entry.getKey());     
 System.out.println( entry.getValue());//Returns the list of values
}

答案 4 :(得分:0)

一次获取所有内容=

List<Integer> list = null;

if(map!= null) 
{ 
  list = new ArrayList<Integer>(map.values()); 
}

存储=

if(map!= null) 
{ 
  list = map.get(keyString); 
   if(list == null)
    {
         list = new ArrayList<Integer>();
    }
  list.add(value);
  map.put(keyString,list);
}

答案 5 :(得分:0)

您可以尝试使用MultiMap而不是HashMap

初始化它将需要更少的代码行。添加和检索值也会缩短它。

Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();

会变成:

Multimap<String, Integer> multiMap = ArrayListMultimap.create();

您可以查看以下链接:http://java.dzone.com/articles/hashmap-%E2%80%93-single-key-and

答案 6 :(得分:0)

在Java中将条目添加到多图(列表的图)的最新方式(截止2020年)是:

map.computeIfAbsent("apple", k -> new ArrayList<>()).add(2);
map.computeIfAbsent("apple", k -> new ArrayList<>()).add(3);

根据Map.computeIfAbsent文档:

如果指定的键尚未与某个值关联(或已映射到null),请尝试使用给定的映射函数计算其值,除非输入null,否则将其输入此映射。 / p>

返回: the current (existing or computed) value associated with the specified key, or null if the computed value is null

迭代列表的最惯用的方法是使用Map.forEachIterable.forEach

map.forEach((k, l) -> l.forEach(v -> /* use k and v here */));

或者,如其他答案所示,是传统的for循环:

for (Map.Entry<String, List<Integer>> e : map.entrySet()) {
    String k = e.getKey();
    for (Integer v : e.getValue()) {
        /* use k and v here */
    }
}
相关问题