从 hashmap 存储和检索 ArrayList 值 [英] Storing and Retrieving ArrayList values from hashmap

查看:31
本文介绍了从 hashmap 存储和检索 ArrayList 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类型的哈希图

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

我想使用迭代器或任何其他方式以最少的代码行存储和获取这些整数.我该怎么做?

I want to store as well as fetch those Integers using Iterator or any other way with minimum lines of code.How can I do it?

编辑 1

数字是随机添加的(不是一起),因为键与相应的行匹配.

The numbers are added at random (not together) as key is matched to the appropriate line.

编辑 2

如何在添加时指向数组列表?

How can I point to the arraylist while adding ?

map.put(string,number);

推荐答案

我们的变量:

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

存储:

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

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

To add numbers one and one, you can do something like this:

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 添加列表:

In Java 8 you can use putIfAbsent to add the list if it did not exist already:

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.
}

这篇关于从 hashmap 存储和检索 ArrayList 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆