Sorting HashMap by values
Assuming Java, you could sort hashmap just like this:
public LinkedHashMap<Integer, String> sortHashMapByValues(
HashMap<Integer, String> passedMap) {
List<Integer> mapKeys = new ArrayList<>(passedMap.keySet());
List<String> mapValues = new ArrayList<>(passedMap.values());
Collections.sort(mapValues);
Collections.sort(mapKeys);
LinkedHashMap<Integer, String> sortedMap =
new LinkedHashMap<>();
Iterator<String> valueIt = mapValues.iterator();
while (valueIt.hasNext()) {
String val = valueIt.next();
Iterator<Integer> keyIt = mapKeys.iterator();
while (keyIt.hasNext()) {
Integer key = keyIt.next();
String comp1 = passedMap.get(key);
String comp2 = val;
if (comp1.equals(comp2)) {
keyIt.remove();
sortedMap.put(key, val);
break;
}
}
}
return sortedMap;
}
Just a kick-off example. This way is more useful as it sorts the HashMap and keeps the duplicate values as well.
How to sort a hashmap by the Integer Value
Try this:
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 4);
map.put("c", 6);
map.put("b", 2);
Object[] a = map.entrySet().toArray();
Arrays.sort(a, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Map.Entry<String, Integer>) o2).getValue()
.compareTo(((Map.Entry<String, Integer>) o1).getValue());
}
});
for (Object e : a) {
System.out.println(((Map.Entry<String, Integer>) e).getKey() + " : "
+ ((Map.Entry<String, Integer>) e).getValue());
}
output:
c : 6
a : 4
b : 2
How to sort a HashMap, values are integers. I want to sort from highest to lowest
You can use Comparator.comparingInt
to sort in the correct order. Streams can be used to sort and collect the new Map
to a LinkedHashMap
to retain the new order.
Map<Player, Integer> result = eloMap.entrySet().stream()
.sorted(Comparator.comparingInt(Map.Entry::getValue))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(a,b)->b, LinkedHashMap::new));
java: sort hashmap by keys and values
you can write your own comparator like below -
class MapValueKeyComparator<K extends Comparable<? super K>, V extends Comparable<? super V>>
implements Comparator<Map.Entry<K, V>> {
public int compare(Map.Entry<K, V> a, Map.Entry<K, V> b) {
int cmp1 = b.getValue().compareTo(a.getValue()); //can reverse a and b position for ascending/descending ordering
if (cmp1 != 0) {
return cmp1;
} else {
return a.getKey().compareTo(b.getKey()); //can reverse a and b position for ascending/descending ordering
}
}
}
Put all the map entries in the list and sort them -
HashMap<String, Integer> map = new HashMap<String, Integer> ();
map.put("Login to new", 27);
map.put("Failed login", 27);
map.put("Impossible", 21);
List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(list, new MapValueKeyComparator<String, Integer>());
for(Map.Entry<String, Integer> m : list){
System.out.println(m);
}
Output -
Failed login=27
Login to new=27
Impossible=21
Explanation - MapValueKeyComparator
sorts key and value of a given map, where values are sorted first and then the keys. In the main code putting all the map entries in the list so that it can be sorted using this comparator by using java's Collections
util class.
How to sort HashMap of String and Integer, by value and in case of duplicate then sort them by key, Including Russian words
I would do something like this:
List<String> sortedEntries = unsortMap.entrySet().stream()
.sorted(Comparator.comparingLong(Map.Entry<String, Integer>::getValue)
.reversed()
.thenComparing(Map.Entry::getKey)
)
.map(it -> it.getKey() + "-" + it.getValue())
.collect(Collectors.toList());
How to sort the hashmap in descending order by values and if the values are the same then by key in ascending order
You can "chain" Comparators by adding calls to thenComparing
:
Map<Integer, Integer> sortedRelevance = new LinkedHashMap<>();
relevance.entrySet()
.stream()
.sorted(Map.Entry.<Integer, Integer> comparingByValue(Comparator.reverseOrder())
.thenComparing(Map.Entry.comparingByKey()))
.forEachOrdered(x -> sortedRelevance.put(x.getKey(), x.getValue()));
Related Topics
Jformattedtextfield Is Not Properly Cleared
When and How to Use a Threadlocal Variable
How to Switch Between Frames in Selenium Webdriver Using Java
What Is a "Surrogate Pair" in Java
Should a Retrieval Method Return 'Null' or Throw an Exception When It Can't Produce the Return Value
How to Kill a Thread? Without Using Stop();
How to Embed a Browser in Java
Problems Using Maven and Ssl Behind Proxy
How to Play .Wav Files with Java
How to Rotate an Image Gradually in Swing
How to Initialise a Static Map
How to Create a Rest Client for Java
Handling Interruptedexception in Java
How to Implement Constants in Java