[英]Sort Map<String, Integer> Largest First Into List<String> Efficiently?
I have a ConcurrentMap<String, Integer>
, and I'd like to get a List<String>
from it with the String mapping to the largest Integer first, second largest second, etc. 我有一个
ConcurrentMap<String, Integer>
,我想从它获得一个List<String>
,其中String映射到最大的Integer第一,第二大,等等。
Right now I have something along the lines of this: 现在我有一些类似的东西:
Loop through the keySet
of the map 循环遍历地图的
keySet
In that loop, loop through a "sorted" List<String>
在该循环中,循环遍历“已排序”
List<String>
Keep looping until the key String's respective value is less than element i
of the "sorted" List
, and insert it. 保持循环,直到键字符串的相应值小于“已排序”
List
元素i
,然后插入它。
Now this will work, but I doubt it's very efficient. 现在这将有效,但我怀疑它是非常有效的。 Does Java 8 have any built in sorting algorithms that could help me here?
Java 8是否有任何内置的排序算法可以帮助我?
Using streams, you could write it like this: 使用流,你可以像这样写:
List<String> sorted = map.entrySet().stream()
.sorted(reverseOrder(comparing(Entry::getValue)))
.map(Entry::getKey)
.collect(toList());
Or as commented by Holger: 或者如Holger评论的那样:
List<String> sorted = map.entrySet().stream()
.sorted(comparingByValue(reverseOrder()))
.map(Entry::getKey)
.collect(toList());
Note static imports: 注意静态导入:
import static java.util.Collections.reverseOrder;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
I don't know if that's more efficient than your method but you can profile both and decide based on actual measurement. 我不知道这是否比你的方法更有效,但你可以分析两者并根据实际测量结果来决定。
Yes, it does. 是的,它确实。 You could do something like this:
你可以这样做:
ConcurrentMap<String, Integer> map = /* something */;
// entrySet just returns a view of the entries, so copy it into a new List
List<Map.Entry<String, Integer>> entries = new ArrayList<>(yourMap.entrySet());
// sort entries by their int values
Collections.sort(entries, (entry1, entry2) -> Integer.compare(entry1.getValue(), entry2.getValue()));
// copy just the keys into a new List
List<String> result = new LinkedList<>();
for (Map.Entry<String, Integer> entry : entries) {
result.add(entry.getKey());
}
import java.util. TreeSet;
import java.util.Set; import java.util.Set; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentHashMap;
public class Test { 公共课测试{
public static void main(String[] args){
ConcurrentHashMap< String, Integer> map = new ConcurrentHashMap<String , Integer>();
map.put("Fish", 1);
map.put("Bird", 100);
map.put("Reptile", 2);
map.put("Mammal", 10);
TreeSet <Integer> sortedList = new TreeSet <Integer>(map.values());
for(Integer i :sortedList){
System.out.println(i);
}
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.