将映射键从集合转换为双精度-Java [英] Convert map key from collection to double - java

查看:79
本文介绍了将映射键从集合转换为双精度-Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Map<String, List<Double>>,从中我想得到一个排序的Map<String, Double>,其中两个映射中的键相同,但第二个映射中的值是第一个映射中值的平均值,然后进行排序.我尝试过:

I have a Map<String, List<Double>> and from this I want to get a SORTED Map<String, Double> where the keys in both maps are the same but the values in the second map are the averages of the values from the first map and then sorted. I’ve tried:

public class ListComparator implements Comparator<List<Double>> {
    public int compare(List<Double> lhs, List<Double>rhs){
        Double lhs_sum = lhs.stream().mapToDouble(a -> a).sum()/lhs.size();
        Double rhs_sum = rhs.stream().mapToDouble(a -> a).sum()/rhs.size();
        return lhs_sum.compareTo(rhs_sum);
    }
}

然后在main()中:

And then in main():

ListComparator listComparator = new ListComparator();
infoMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(listComparator))
                .limit(15).forEach(System.out::println);

但是这会打印出密钥,并出现一个未排序的数量可变的双精度数组(应该是一个双精度数组).我错过了哪一步? 谢谢

But this prints out the key and, it appears, an array of varying number of doubles (should be one double only) that are not sorted. What step am I missing? Thanks

推荐答案

您只能进行比较,但是我看不到将平均值放在输出中的位置.

You only comparing, but I didn't see where you put the average to the output.

尝试一下:

infoMap.entrySet().stream()
       .map(e -> new SimpleEntry<>(e.getKey(),
                                   e.getValue().stream()
                                    .mapToDouble(d -> d).average()
                                    .orElse(0d)))
       .sorted(Comparator.comparingDouble(Entry::getValue))
       .collect(Collectors.toMap(Entry::getKey, Entry::getValue, 
                                (v1, v2) -> v1, LinkedHashMap::new));

因此,您看到的第一步是将每个条目转换为SimpleEntry<String, Double>,其中值是列表的平均值.

So you see, the first step is convert each entry to a SimpleEntry<String, Double> where value is the average of the list.

第二步是按Entry::getValue

然后最后,将它们收集回新的Map<String, Double>

Then finally, collect them back to a new Map<String, Double>

这篇关于将映射键从集合转换为双精度-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆