How to convert a Map<String, Double>
to List<Pair<String, Double>>
in Java 8?
I wrote this implementation, but it is not efficient
Map<String, Double> implicitDataSum = new ConcurrentHashMap<>();
//....
List<Pair<String, Double>> mostRelevantTitles = new ArrayList<>();
implicitDataSum.entrySet().stream().
.sorted(Comparator.comparing(e -> -e.getValue()))
.forEachOrdered(e -> mostRelevantTitles.add(new Pair<>(e.getKey(), e.getValue())));
return mostRelevantTitles;
I know that it should works using .collect(Collectors.someMethod())
. But I don't understand how to do that.
Well, you want to collect Pair
elements into a List
. That means that you need to map your Stream<Map.Entry<String, Double>>
into a Stream<Pair<String, Double>>
.
This is done with the map
operation:
Returns a stream consisting of the results of applying the given function to the elements of this stream.
In this case, the function will be a function converting a Map.Entry<String, Double>
into a Pair<String, Double>
.
Finally, you want to collect that into a List
, so we can use the built-in toList()
collector.
List<Pair<String, Double>> mostRelevantTitles =
implicitDataSum.entrySet()
.stream()
.sorted(Comparator.comparing(e -> -e.getValue()))
.map(e -> new Pair<>(e.getKey(), e.getValue()))
.collect(Collectors.toList());
Note that you could replace the comparator Comparator.comparing(e -> -e.getValue())
by Map.Entry.comparingByValue(Comparator.reverseOrder())
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments