shanlodh
shanlodh

Reputation: 1045

Convert map key from collection to double - java

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

Upvotes: 2

Views: 2493

Answers (1)

Mạnh Quyết Nguyễn
Mạnh Quyết Nguyễn

Reputation: 18235

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>

Upvotes: 2

Related Questions