Java - 在不覆盖的情况下向现有 HashMap 键添加另一个字符串值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29717234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - Adding another String value to existing HashMap Key without overwriting?
提问by jxc
I was wondering if someone would be able to help with regards to adding another String
value to an existing key within a HashMap
in Java?
我想知道是否有人能够帮助在 Java 中为String
aHashMap
中的现有键添加另一个值?
I understand that you can add a Key-Value pair using the this.put("String", "String")
method. However, it overwrites the existing value, whereas I would like multiple values stored and paired, with the same key?
我知道您可以使用该this.put("String", "String")
方法添加键值对。但是,它会覆盖现有值,而我希望使用相同的键存储和配对多个值?
Thanks for your help.
谢谢你的帮助。
采纳答案by SCB
What are you hoping to achieve here?
你希望在这里实现什么?
A Map
(the HashMap
) in your case is a direct "mapping" from one "key" to another value.
A Map
(the HashMap
) 在您的情况下是从一个“键”到另一个值的直接“映射”。
E.g.
例如
"foo" -> 123
"bar" -> 321
"far" -> 12345
"boo" -> 54321
This means that if you were to try:
这意味着,如果您要尝试:
myHashMap.get("foo");
It would return the value 123
(of course, the type of the value you return can be anything you want).
它将返回值123
(当然,您返回的值的类型可以是您想要的任何类型)。
Of course, this also means that any changes you make to the value of the key, it overrides the original value you assigned it, just like changing the value of a variable will override the original one assigned.
当然,这也意味着您对键的值所做的任何更改,它都会覆盖您分配给它的原始值,就像更改变量的值将覆盖原始分配的值一样。
Say:
说:
myHashMap.put("foo", 42);
The old value of "foo"
in the map would be replaced with 42
. So it would become:
"foo"
地图中的旧值将替换为42
。所以它会变成:
"foo" -> 42
"bar" -> 321
"far" -> 12345
"boo" -> 54321
However, if you need multiple String
objects that are mapped from a single key, you could use a different object which can store multiple objects, such as an Array or a List (or even another HashMap
if you wanted.
但是,如果您需要String
从单个键映射的多个对象,则可以使用可以存储多个对象的不同对象,例如数组或列表(HashMap
如果需要,甚至可以使用另一个对象。
For example, if you were to be using ArrayLists
, when you are assigning a value to the HashMap
, (say it is called myHashMap
), you would first check if the key has been used before, if it hasn't, then you create a new ArrayList
with the value you want to add, if it has, then you just add the value to the list.
例如,如果您要使用ArrayLists
,当您为 分配一个值时HashMap
,(假设它被称为myHashMap
),您将首先检查该键之前是否已使用过,如果尚未使用,则您创建一个新ArrayList
的要添加的值(如果有),则只需将该值添加到列表中。
(Assume key
and value
have the values you want)
(假设key
并value
拥有您想要的值)
ArrayList<String> list;
if(myHashMap.containsKey(key)){
// if the key has already been used,
// we'll just grab the array list and add the value to it
list = myHashMap.get(key);
list.add(value);
} else {
// if the key hasn't been used yet,
// we'll create a new ArrayList<String> object, add the value
// and put it in the array list with the new key
list = new ArrayList<String>();
list.add(value);
myHashMap.put(key, list);
}
回答by EvenLisle
Would you like a concatenation of the two strings?
你想连接两个字符串吗?
map.put(key, val);
if (map.containsKey(key)) {
map.put(key, map.get(key) + newVal);
}
Or would you like a list of all the values for that key?
或者您想要该键的所有值的列表?
HashMap<String,List<String>> map = new HashMap<String,List<String>>();
String key = "key";
String val = "val";
String newVal = "newVal";
List<String> list = new ArrayList<String>();
list.add(val);
map.put(key, list);
if (map.containsKey(key)) {
map.get(key).add(newVal);
}
回答by M Sach
Store value as list under map So if key is test and there are two values say val1 and val2 then key will be test and value will be list containing val1 and val2
将值存储为地图下的列表所以如果键是测试并且有两个值说 val1 和 val2 那么键将是测试并且值将是包含 val1 和 val2 的列表
But if your intention is to have two separate entries for same key, then this is not Map is designed for. Think if you do map.get("key"), which value you expects
但是,如果您打算为同一个键创建两个单独的条目,那么这不是 Map 的设计目标。想想如果你做map.get("key"),你期望哪个值
回答by Fellrond
As described in Map interface documentationMap contains a set of keys, so it is not capable of containing multiple non-unique keys.
如Map 接口文档中所述,Map包含一组键,因此它不能包含多个非唯一键。
I suggest you to use lists as values for this map.
我建议您使用列表作为此地图的值。
回答by nikis
As others pointed, Map
by specification can have only one value for a given key. You have 2 solutions:
正如其他人指出的那样,Map
根据规范,给定的键只能有一个值。您有 2 个解决方案:
- Use
HashMap<String, List<String>>
to store the data - Use Multimapwhich is provided by 3rd party Google Collections lib
- 使用
HashMap<String, List<String>>
存储数据 - 使用由 3rd 方 Google Collections lib 提供的Multimap
回答by Sankozi
回答by Moldova
You can't directly store multiple values under a single key, but the value associated with a key can be any type of object, such as an ArrayList, which will hold multiple values. For example:
您不能直接在单个键下存储多个值,但与键关联的值可以是任何类型的对象,例如 ArrayList,它将保存多个值。例如:
import java.util.ArrayList;
import java.util.HashMap;
public class HashMapList {
HashMap<String, ArrayList<String>> strings = new HashMap<String, ArrayList<String>>();
public void add(String key, String value) {
ArrayList<String> values = strings.get(key);
if (values == null) {
values = new ArrayList<String>();
strings.put(key, values);
}
values.add(value);
}
public ArrayList<String> get(String key) {
return strings.get(key);
}
public static void main(String[] argv) {
HashMapList mymap = new HashMapList();
mymap.add("key", "value1");
mymap.add("key", "value2");
ArrayList<String> values = mymap.get("key");
for (String value : values) {
System.out.println(value);
}
}
}
回答by Gospel
it's impossible,because String is immutable if you use the String as the key of map the same key's value has the same hashcode value.
这是不可能的,因为 String 是不可变的,如果您使用 String 作为映射的键,则相同键的值具有相同的哈希码值。
回答by Prashanth Terala
You can do like this!
你可以这样做!
Map<String,List<String>> map = new HashMap<>();
.
.
if(map.containsKey(key)){
map.get(key).add(value);
} else {
List<String> list = new ArrayList<>();
list.add(value);
map.put(key, list);
}
Oryou can do the same thing by one line code in Java 8 style .
或者您可以通过 Java 8 风格的一行代码来做同样的事情。
map.computeIfAbsent(key, k ->new ArrayList<>()).add(value);