如何在Java 8中将Map转换为List

Yak*_*vko 14 java java-8 java-stream

如何将转换Map<String, Double>List<Pair<String, Double>>使用Java 8?

我写了这个实现,但效率不高

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;
Run Code Online (Sandbox Code Playgroud)

我知道它应该可以使用.collect(Collectors.someMethod()).但我不明白该怎么做.

Tun*_*aki 20

好吧,你想收集Pair元素List.这意味着您需要将您映射Stream<Map.Entry<String, Double>>到一个Stream<Pair<String, Double>>.

这是通过以下map操作完成的:

返回一个流,该流包含将给定函数应用于此流的元素的结果.

在这种情况下,该函数将是一个将a转换Map.Entry<String, Double>为a 的函数Pair<String, Double>.

最后,你想把它收集到一个List,所以我们可以使用内置的toList()收集器.

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());
Run Code Online (Sandbox Code Playgroud)

请注意,您可以取代比较Comparator.comparing(e -> -e.getValue())Map.Entry.comparingByValue(Comparator.reverseOrder()).


Tag*_*eev 6

请注意,如果您想要有效实施,您应该考虑这个:

List<Pair<String, Double>> mostRelevantTitles = 
    implicitDataSum.entrySet()
                   .stream()
                   .map(e -> new Pair<>(e.getKey(), e.getValue()))
                   .collect(Collectors.toList());
mostRelevantTitles.sort(Comparators.comparing(Pair::getSecond, Comparator.reverseOrder()));
Run Code Online (Sandbox Code Playgroud)

我认为你的Pair班级有getSecond吸气剂.

使用sorted()流管道步骤创建中间缓冲区,将所有内容存储到该缓冲区,将其转换为数组,对该数组进行排序,然后将结果存储到ArrayList.我的方法尽管功能较少,但会将数据直接存储到目标中ArrayList,然后在不进行任何额外复制的情况下对其进行排序.所以我的解决方案将花费更少的时间和中间记忆.