![java-how-to-sort-a-map-on-the-values]()
In Java How to sort a Map on Value? There are number of ways. Here we will follow below steps.
public interface Map<K,V>
An object
that maps keys
to values
. A map
cannot contain duplicate keys; each key can map to at-most
one value. HashMap to ArrayList? The Map
interface provides three collection views, which allow a map’s contents to be viewed as a set of keys, collection of values, or set of key-value mappings.
There is another way to use Google Guava Library
which contains several of Google’s core libraries that we rely on in our Java-based projects: collections, caching, primitives support, concurrency libraries, common annotations, string processing, I/O, and so forth.
Here is an example on Google Guava Library.
The order of a map is defined as the order in which the iterators on the map’s collection views return their elements. Some map implementations, like the TreeMap
class, make specific guarantees as to their order; others, like the HashMap
class, do not.
Let’s take a look at below steps and example
- Create file
CrunchifyMapUtil.java
- We will create
crunchifySortMap
function uses LinkedHashMap
which keep the insertion order
- Main method in which we will create one Map
initialCrunchifyMapValue
with random Integer value
- Pass
initialCrunchifyMapValue
to crunchifySortMap
which returns sorted map called sortedCrunchifyMapValue
- Now we will iterate through both map to see result
package crunchify.com.tutorials;
import java.util.*;
/**
* @author Crunchify.com
*
*/
public class CrunchifyMapUtil {
/*
* Sort a map according to values.
*
* @param <K> the key of the map.
*
* @param <V> the value to sort according to.
*
* @param crunchifySortMap the map to sort.
*
* @return a map sorted on the values.
*/
public static <K, V extends Comparable<? super V>> Map<K, V> crunchifySortMap(final Map<K, V> mapToSort) {
List<Map.Entry<K, V>> entries = new ArrayList<Map.Entry<K, V>>(mapToSort.size());
entries.addAll(mapToSort.entrySet());
// Sorts the specified list according to the order induced by the specified comparator
Collections.sort(entries, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(final Map.Entry<K, V> entry1, final Map.Entry<K, V> entry2) {
// Compares this object with the specified object for order
return entry1.getValue().compareTo(entry2.getValue());
}
});
Map<K, V> sortedCrunchifyMap = new LinkedHashMap<K, V>();
// The Map.entrySet method returns a collection-view of the map
for (Map.Entry<K, V> entry : entries) {
sortedCrunchifyMap.put(entry.getKey(), entry.getValue());
}
return sortedCrunchifyMap;
}
public static void main(String args[]) {
Random random = new Random(System.currentTimeMillis());
// Variable with size 10
Map<String, Integer> initialCrunchifyMapValue = new HashMap<String, Integer>(10);
for (int i = 0; i < 10; ++i) {
initialCrunchifyMapValue.put("Crunchify # " + i, random.nextInt(500));
}
log("Initial CrunchifyMapValue ========== \n");
for (Map.Entry<String, Integer> entry : initialCrunchifyMapValue.entrySet()) {
log(entry.getKey() + "\t" + entry.getValue());
}
Map<String, Integer> sortedCrunchifyMapValue = new HashMap<String, Integer>(10);
// Sort Map on value by calling crunchifySortMap()
sortedCrunchifyMapValue = CrunchifyMapUtil.crunchifySortMap(initialCrunchifyMapValue);
log("\nSorted CrunchifyMapValue ========== \n");
for (Map.Entry<String, Integer> entry : sortedCrunchifyMapValue.entrySet()) {
log(entry.getKey() + "\t" + entry.getValue());
}
}
private static void log(String value) {
System.out.println(value);
}
}
Eclipse Console Result:
Initial CrunchifyMapValue: ==========
Crunchify # 0 271
Crunchify # 1 126
Crunchify # 2 83
Crunchify # 3 462
Crunchify # 4 123
Crunchify # 5 393
Crunchify # 6 40
Crunchify # 7 65
Crunchify # 8 82
Crunchify # 9 437
Sorted CrunchifyMapValue ==========
Crunchify # 6 40
Crunchify # 7 65
Crunchify # 8 82
Crunchify # 2 83
Crunchify # 4 123
Crunchify # 1 126
Crunchify # 0 271
Crunchify # 5 393
Crunchify # 9 437
Crunchify # 3 462
The post In Java How to Sort a Map on the Values? The Map Interface – Java Collections appeared first on Crunchify.