java 如何在java中为单个键添加多个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44241813/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:01:42  来源:igfitidea点击:

how to add multiple values to single key in java

java

提问by Ock

How can I create a map that can extend its list of value. For example I have a map which contains: key A and list of values B {1,2,3}. Then at some point during the program running, I would like to add more value, ex: 4 to list B. Now my new map should be something like: (A,{1,2,3,4}). How can I do that?

如何创建可以扩展其值列表的地图。例如,我有一张地图,其中包含:键 A 和值列表 B {1,2,3}。然后在程序运行的某个时刻,我想添加更多值,例如:4 到列表 B。现在我的新地图应该是这样的:(A,{1,2,3,4})。我怎样才能做到这一点?

回答by dasblinkenlight

Since Map<K,V>maps one key to one value, you need Vto be of type List<T>:

由于Map<K,V>将一个键映射到一个值,因此您需要V具有以下类型List<T>

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

One consequence of having a type like that is that now the process of adding an item to a key consists of two steps: you must check if the list for the key exists, and then either add a new item to an existing list, or add a new list with a single item:

拥有这样的类型的一个后果是,现在向键添加项的过程包括两个步骤:您必须检查键的列表是否存在,然后向现有列表添加新项,或添加包含单个项目的新列表:

List<Integer> current = multiMap.get(key);
if (current == null) {
    current = new ArrayList<Integer>();
    multiMap.put(key, current);
}
current.add(val);

If you use Java 8, you can use computeIfAbsentto greatly simplify the code:

如果你使用Java 8,你可以使用computeIfAbsent来大大简化代码:

multiMap.computeIfAbsent(key, k -> new ArrayList<>()).add(value);

回答by Vinod

Add new Integer using new temp variable, Check with this explains might be help.

使用新的临时变量添加新的整数,检查这个解释可能会有所帮助。

    Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
    List<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(2);
    list.add(3);

    map.put("A", list);
    map.forEach((key,value)->System.out.print(key + " : "+
    value));
    List<Integer> newList = (ArrayList<Integer>)map.get("A");
    newList.add(4);
    System.out.println();
    map.put("A", newList);
    map.forEach((key,value)->System.out.print(key + " : "+
            value));

回答by Sergey Prokofiev

Such type of collection already implemented. Take a look at Multimap from Guava. Don't invent the bike from the scratch.

这种类型的收集已经实施。看看来自 Guava 的 Multimap。不要从头开始发明自行车。

Hope it helps!

希望能帮助到你!

回答by Norbert

A more generic solution is to have a MultiMap class which provides any Collection type as value e.g. ArrayList: I found this in a Java-Book weeks ago. Example:

一个更通用的解决方案是拥有一个 MultiMap 类,它提供任何 Collection 类型作为值,例如 ArrayList:我几周前在 Java-Book 中发现了这个。例子:

class MultiMap<K, V> 
{
  private final Map<K,Collection<V>> map = new HashMap<>();

  public Collection<V> get(K key) 
  {
    return map.getOrDefault(key, Collections.<V> emptyList());
  }
  public void put(K key,V value )
  {
    map.computeIfAbsent( key, k -> new ArrayList<>()).add( value );
  }
}

Usage may be: (the map value is a ArrayList of Strings)

用法可能是:(映射值是字符串的 ArrayList)

MultiMap<Integer,String> map = new MultiMap<>();
int id = 34;
System.out.println(map.get(id)); // creates an ArrayList<String> for key 34

map.put(id,"first value for 34");
System.out.println(map.get(id)); // [first value for 34]

map.put(id,"second");
System.out.println(map.get(id)); // [first value for 34, second]

Hope this helps...

希望这可以帮助...

回答by Alekya

 public static void main(String[] args) {

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

List<String> valSetOne = new ArrayList<String>();
valSetOne.add("ABC");
valSetOne.add("BCD");
valSetOne.add("DEF");

List<String> valSetTwo = new ArrayList<String>();
valSetTwo.add("CBA");
valSetTwo.add("DCB");

map.put("FirstKey", valSetOne);
map.put("SecondKey", valSetTwo);

for (Map.Entry<String, List<String>> entry : map.entrySet()) {

    String key = entry.getKey();

    List<String> values = entry.getValue();

    System.out.println("Value of " + key + " is " + values);

}

}

}

You can use Set or List based on your requirement.This is a simple method of having single key with multiple values.

您可以根据您的要求使用 Set 或 List。这是一种具有多个值的单个键的简单方法。

回答by SanSan-

Java 8. Stream API.

Java 8. 流 API。

For example we have collection of Users as List:

例如,我们将用户集合作为列表:

[{ name: "qwer", surname: "asdf", type: "premium"}, { name: "ioup", surname: "vmnv", type: "usual"}, { name: "rtyr", surname: "zxc", type: "premium"}] 

and we need to add multiple Users to Map where key is ?type?

并且我们需要将多个用户添加到 Map 其中键是?type?

Map<String, List<User>> map = collection.stream().collect(Collectors.groupingBy(User::getType, Collectors.mapping(Function.identity(), Collectors.toList())))

To process this map we can make new stream

为了处理这张地图,我们可以制作新的流

map.entrySet().stream().{map|reduce|& other things}...