简体   繁体   English

使用哈希图比较键和值,并基于相似的键将值相加

[英]Using Hashmaps to compare keys and values and add together values based on similar keys

So i was wondering how and if it was possible using Hashmaps, one containing only strings and the other containing a similar string key but a float value, to compare them and then from that comparison print out the amount of similar values in the first hashmap, and then the float from the second hashmap added together when their keys/values line up. 因此,我想知道如何以及是否可以使用Hashmaps(一个仅包含字符串,另一个包含类似的字符串键但包含一个浮点值)进行比较,然后从该比较中打印出第一个hashmap中的相似值的数量,然后当键/值对齐时,第二个哈希图中的浮点数加在一起。 Example below that should clarify what i mean and to do this dynamically. 下面的示例应阐明我的意思并动态地执行此操作。

CODE

HashMap<String, String> hmap = new HashMap<>();
HashMap<String, Float> h2map = new HashMap<>();
hmap.put("order1", "pending");
hmap.put("order2", "cancelled");
hmap.put("order3", "pending");

h2map.put("order1", (float) 19.95);
h2map.put("order2", (float) 19.95);
h2map.put("order3", (float) 39.9);

Set <String> singles = new HashSet<>(h2map.values());

if(h2map.keySet().equals(hmap.keySet())) {
// below prints out the states and amount of the states but how can i get the float values from hmap to be added together for the similar states and printed with their respective state?
  for(String element : singles) {               
   System.out.println(element + ": " + Collections.frequency(hmap.values(), element));          
                    }
}

Current Output 电流输出

pending: 2
cancelled: 1

Desired Output 期望的输出

pending: 2 $59.85
cancelled 1 $19.95

Is this what you want? 这是你想要的吗?

public static void main(String[] args) {
    HashMap<String, String> hmap = new HashMap<>();
    HashMap<String, Float> h2map = new HashMap<>();

    hmap.put("order1", "pending");
    hmap.put("order2", "cancelled");
    hmap.put("order3", "pending");

    h2map.put("order1", 19.95f);
    h2map.put("order2", 19.95f);
    h2map.put("order3", 39.9f);

    Map<String, DoubleSummaryStatistics> grouping = hmap
            .entrySet()
            .stream()
            .collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.summarizingDouble(e -> h2map.get(e.getKey()))));

    grouping.forEach((key, value) -> System.out.println(key + ": " + value.getCount() + " " + value.getSum()));
}

Note that there is no summarizing statistics collector for BigDecimal and this code works only with Float or Double. 请注意,BigDecimal没有汇总统计信息收集器,并且此代码仅适用于Float或Double。 But for money calculations better use BigDecimal. 但是对于金钱计算,最好使用BigDecimal。 It's possible to implement the custom collector if needed ) 如果需要,可以实现自定义收集器

I have replaced the use of Float with BigDecimal for better accuracy. 为了更好的准确性,我用BigDecimal代替了Float的用法。 Also I used two maps, one for holding the summed value and the other for count: 我还使用了两个映射,一个用于保存总和,另一个用于计数:

public static void main(String[] args) {
        HashMap<String, String> hmap = new HashMap<>();
        HashMap<String, BigDecimal> h2map = new HashMap<>();
        hmap.put("order1", "pending");
        hmap.put("order2", "cancelled");
        hmap.put("order3", "pending");

        h2map.put("order1", new BigDecimal("19.95"));
        h2map.put("order2", new BigDecimal("19.95"));
        h2map.put("order3", new BigDecimal("39.9"));

        //Map for holding sum 
        HashMap<String, BigDecimal> sum = new HashMap<>();

        for(String key : h2map.keySet()){
            if(hmap.get(key) != null){
                String value = hmap.get(key);
                if(sum.get(value) == null){
                    sum.put(value, h2map.get(key));
                }else{
                    sum.put(value, (sum.get(value).add(h2map.get(key))));
                }
            }
        }
        //Map for holding count
        HashMap<String, BigDecimal> countMap = new HashMap<>();
        for(Iterator<Map.Entry<String, BigDecimal>> itr = sum.entrySet().iterator(); itr.hasNext(); ){
            Map.Entry<String, BigDecimal> entry = itr.next();
            String key = entry.getKey();
            int count = Collections.frequency(hmap.values(), key);
            countMap.put((key + count), sum.get(key));
            itr.remove();
        }
        //For GC
        sum = null;
        countMap.forEach((k, v) -> System.out.println(k + " " + v));
    }

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM