Sorting Map <String, Integer> Largest First in List <String> Efficient?
I have ConcurrentMap<String, Integer>
, and I would like to get from it List<String>
with a String mapping to the largest integer first, second largest second, etc.
Now I have something like this:
Loop through the keySet
cards
In this loop, loop through the "sorted" List<String>
loop Continue the loop until the corresponding String value is less than the i
"sorted" item List
and insert it.
Now this will work, but I doubt it is very effective. Does Java 8 have built-in sorting algorithms that can help me here?
source to share
Using streams, you can write it like this:
List<String> sorted = map.entrySet().stream()
.sorted(reverseOrder(comparing(Entry::getValue)))
.map(Entry::getKey)
.collect(toList());
Or, as Holger commented:
List<String> sorted = map.entrySet().stream()
.sorted(comparingByValue(reverseOrder()))
.map(Entry::getKey)
.collect(toList());
Pay attention to 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 this is more efficient than your method, but you can profile both and decide based on the actual measurement.
source to share
Yes Yes. You can 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());
}
source to share
import java.util. TreeSet;
import java.util.Set; 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);
}
}
}
source to share