Convert map key from collection to double - java

不羁的心 提交于 2020-01-04 05:36:17

问题


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);
    }
}

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


回答1:


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

Try this:

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));

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

The second step is sort those mapped entries by Entry::getValue

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



来源:https://stackoverflow.com/questions/51919967/convert-map-key-from-collection-to-double-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!