将值添加到 Map 中已存在的键的列表中

Adding a value to a list to an already existing key in Map(将值添加到 Map 中已存在的键的列表中)
本文介绍了将值添加到 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 中已存在的键的列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)