简体   繁体   English

两个Map之和的最佳方法是什么? <String,String> ?

[英]What's the best way to sum two Map<String,String>?

I have the following maps. 我有以下地图。

Map<String,String> map1= new HashMap<String, String>(){{
       put("no1","123"); put("no2","5434"); put("no5","234");}};

Map<String,String> map1 = new HashMap<String, String>(){{
       put("no1","523"); put("no2","234"); put("no3","234");}};

sum(map1, map2);

I want to join them to one, summing up similar keyed values together. 我想将它们加入到一个中,将类似的键值一起总结。 What;s the best way I could do it using java 7 or guava libraries ? 什么;使用java 7或guava库我能做到的最好的方法是什么?

expected output 预期产出

Map<String, String> output = { { "no1" ,"646"}, { "no2", "5668"}, {"no5","234"}, {"no3","234" }  }
private static Map<String, String> sum(Map<String, String> map1, Map<String, String> map2) {
        Map<String, String> result = new HashMap<String, String>();
        result.putAll(map1);
        for (String key : map2.keySet()) {
            String value = result.get(key);
            if (value != null) {
                Integer newValue = Integer.valueOf(value) + Integer.valueOf(map2.get(key));
                result.put(key, newValue.toString());
            } else {
                result.put(key, map2.get(key));
            }
        }
        return result;
    }

try this 尝试这个

    Map<String, List<String>> map3 = new HashMap<String, List<String>>();
    for (Entry<String, String> e : map1.entrySet()) {
        List<String> list = new ArrayList<String>();
        list.add(e.getValue());
        String v2 = map2.remove(e.getKey());
        if (v2 != null) {
            list.add(v2);
        }
        map3.put(e.getKey(), list);
    }

    for (Entry<String, String> e : map2.entrySet()) {
        map3.put(e.getKey(), new ArrayList<String>(Arrays.asList(e.getValue())));
    }

Java 8 introduces Map.merge(K, V, BiFunction) , which makes this easy if not particularly concise: Java 8引入了Map.merge(K,V,BiFunction) ,这使得这很容易,如果不是特别简洁:

Map<String, String> result = new HashMap<>(map1);
//or just merge into map1 if mutating it is okay
map2.forEach((k, v) -> result.merge(k, v, (a, b) ->
    Integer.toString(Integer.parseInt(a) + Integer.parseInt(b))));

If you're doing this repeatedly, you're going to be parsing and creating a lot of strings. 如果你反复这样做,你将要解析并创建很多字符串。 If you're generating the maps one at a time, you're best off maintaining a list of strings and only parsing and summing once. 如果你一次只生成一个地图,你最好保持一个字符串列表,只解析和求和一次。

Map<String, List<String>> deferredSum = new HashMap<>();
//for each map
mapN.forEach((k, v) ->
    deferredSum.computeIfAbsent(k, x -> new ArrayList<String>()).add(v));
//when you're done
Map<String, String> result = new HashMap<>();
deferredSum.forEach((k, v) -> result.put(k,
    Long.toString(v.stream().mapToInt(Integer::parseInt).sum())));

If this summing is a common operation, consider whether using Integer as your value type makes more sense; 如果这个求和是一个常见的操作,请考虑使用Integer作为您的值类型是否更有意义; you can use Integer::sum as the merge function in that case, and maintaining lists of deferred sums would no longer be necessary. 在这种情况下,您可以使用Integer::sum作为合并函数,并且不再需要维护延迟总和列表。

Try this 尝试这个

    Map<String,String> map1= new HashMap<String, String>(){{
        put("no1","123"); put("no2","5434"); put("no5","234");}};
    Map<String,String> map2 = new HashMap<String, String>(){{
        put("no1","523"); put("no2","234"); put("no3","234");}};
    Map<String,String> newMap=map1;
    for(String a:map2.keySet()){
       if(newMap.keySet().contains(a)){
               newMap.put(a,""+(Integer.parseInt(newMap.get(a))+Integer.parseInt(map2.get(a))));
       }
        else{
            newMap.put(a,map2.get(a));
        }
    }
    for(String k : newMap.keySet()){
        System.out.println("key : "+ k + " value : " + newMap.get(k));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 什么是定义地图的最佳方法 <String, Map<String, String> &gt;用Java映射? - What would be the best way to define a Map<String, Map<String, String>> map in Java? 在地图中获取前N个元素的最佳方法是什么 <String, Double> 根据他们的价值观? - What's the best way to get top N elements in a Map<String, Double> based on their values? 将此字符串转换为字符串数组的最佳方法是什么? - What's the best way to convert this string into a string array? 在 Java 中构建一串分隔项的最佳方法是什么? - What's the best way to build a string of delimited items in Java? 检查 String 是否包含 Java/Android 中的 URL 的最佳方法是什么? - What's the best way to check if a String contains a URL in Java/Android? 什么是将double序列化为字符串并再次返回的最佳方法? - What's the best way to serialize a double to a string and back again? 缩写匹配字符串的最佳方法是什么 - What's the best way to match a string by its abbreviation 在 Java 中检查 String 是否代表整数的最佳方法是什么? - What's the best way to check if a String represents an integer in Java? 将ContentValues转换为JSON字符串的最佳(最简单)方法是什么? - What's the best (easiest) way to convert ContentValues to a JSON string? 使用 Java 保护查询字符串的最佳方法是什么? - What's the best way to secure a query string with Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM