合并映射并将值作为数组

时间:2017-12-04 11:38:13

标签: java arrays collections

public class MapCheck {
    public static void main(String[] args) {
        Map<String, String> data = new HashMap<String, String>();
        data.put("John", "Taxi Driver");
        data.put("Mark", "Professional Killer");
        Map<String, String> data1 = new HashMap<String, String>();
        data1.put("John", "Driver");
        data1.put("Mark", "Murderer");
        Map<String, String> data3 = new HashMap<String, String>();
        data3.putAll(data);
        data3.putAll(data1);
        System.out.println(data3);
    }
}

我有几张包含相同键的地图,它们的值不同。我想合并他们。但是当我将它们与通常的putAll()合并时,它只给出了最新插入的键的值。

以上代码的输出为{John=Driver, Mark=Murderer}

是否有一种方法可以获取与该键相关的所有值,并将其作为数组提供给我

{John=[Taxi Driver, Driver], Mark=[Professional Killer, Murderer]}

4 个答案:

答案 0 :(得分:5)

使用Java 8 Map<String, List<String>> s:

可以非常轻松地生成Stream
Map<String, List<String>>
    merged =
        Stream.of(data,data1) // create a Stream<Map<String,String> of all Maps
              .flatMap(map->map.entrySet().stream()) // map all the entries of all the
                                                     // Maps into a 
                                                     // Stream<Map.Entry<String,String>>
              .collect(Collectors.groupingBy(Map.Entry::getKey, // group entries by key
                                             Collectors.mapping(Map.Entry::getValue,
                                                                Collectors.toList())));

输出Map

{John=[Taxi Driver, Driver], Mark=[Professional Killer, Murderer]}

答案 1 :(得分:2)

这样的东西?

void add(String key, String value, Map<String,List<String>> map) {
    List<String> list = map.get(key);
    if (list == null) {
        list = new ArrayList<>();
        map.put(key, list);
    }
    list.add(value);
}

答案 2 :(得分:1)

您可能想要创建Map<String, <ArrayList<String>>。这样,您可以存储与一个键关联的多个值。

您可以考虑创建一种方法,该方法提供存储与指定地图中唯一键相关联的多个值:

public static void add(String key, String value, Map<String, List<String>> map) {
        // Here you create a refeREnce to instance of the list storing values associated with given key:
        List<String> listOfValues = map.get(key);
        // If given key was already present in the map...
        if(listOfValues != null) {
            // Add given value to list of values associated with given key:
            listOfValues.add(value);
        // If given key wasn't present in the map...
        } else {
            // Initialize an ArrayList that will store given value in the map:
            listOfValues = new ArrayList<>();
            // Put new entry into the given map (given key and to-be-filled list of values:
            map.put(key, listOfValues);
            // Put given value to the list of values associated with given key
            listOfValues.add(value);
        }
}

答案 3 :(得分:1)

数据结构$('.select2').val('').trigger("change"); 可能是最佳选择。强烈建议在番石榴中实施 https://github.com/google/guava/wiki/NewCollectionTypesExplained#multimap