将值添加到Map中已存在的键的列表中 [英] Adding a value to a list to an already existing key in Map

查看:300
本文介绍了将值添加到Map中已存在的键的列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

晚上!

我有以下地图:

HashMap<String, ArrayList> myMap = new HashMap<String, ArrayList>();

然后我向其中添加了以下数据:

I then added the following data to it:

ArrayList myList = new ArrayList();
myList.add("Test 1");
myList.add("Test 2");
myList.add("Test 3");
myMap.put("Tests", myList);

这给我留下了以下数据:

This left me with the following data:

键:测试

:测试1,测试2,测试3

Values: Test 1, Test 2, Test 3

我的问题是,然后如何将新值添加到我现有的键上?因此,例如,如何将值"Test 4"添加到键"Tests"上.

My question is, how do I then add new values on to my already existing key? So for example, how could I add the value "Test 4" onto my key "Tests".

谢谢.

推荐答案

只需从地图中获取列表,然后将元素添加到列表中即可.

Simply get the list from the map and then add the element to the list:

ArrayList list = myMap.get("Tests");
list.add("Test4");

关于您的代码,还有一些其他事情需要说明.首先,不要使用原始的 ArrayList.使用泛型:

There are some other things that can be remarked about your code. First of all, don't use the raw type ArrayList. Use generics:

HashMap<String, ArrayList<String>> myMap = new HashMap<String, ArrayList<String>>();

ArrayList<String> myList = new ArrayList<String>();
myList.add("Test 1");
myList.add("Test 2");
myList.add("Test 3");
myMap.put("Tests", myList);

第二,编程到接口,而不是实现.换句话说,使用接口MapList而不是实现HashMapArrayList进行编程.这是众所周知的OO编程原理,例如,在必要时可以更轻松地切换到其他实现.

Second, program to interfaces, not implementations. In other words, program using interfaces Map and List rather than the implementations HashMap and ArrayList. This is a well-known OO programming principle, which makes it for example easier to switch to a different implementation, if necessary.

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

List<String> myList = new ArrayList<String>();
myList.add("Test 1");
myList.add("Test 2");
myList.add("Test 3");
myMap.put("Tests", myList);

最后,提供语法提示:如果您使用的是Java 7或更高版本,则可以使用<>,而不必重复输入类型参数:

Finally, a syntax tip: if you're using Java 7 or newer you can use <> and you don't have to repeat the type arguments:

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

List<String> myList = new ArrayList<>();
myList.add("Test 1");
myList.add("Test 2");
myList.add("Test 3");
myMap.put("Tests", myList);

myMap.get("Tests").add("Test 4");

这篇关于将值添加到Map中已存在的键的列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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