Sort a Map by value !!

Sorting a Map by value in Java:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class SortMapByValue {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("z", 2);
map.put("q", 0);
map.put("p", 5);
map.put("s", 8);
map.put("o", 0);
map.put("r", 9);
map.put("v", 8);
System.out.println(map);
Set<Entry<String, Integer>> entrySet = map.entrySet();
List<Entry<String, Integer>> lists = new ArrayList<Entry<String, Integer>>(entrySet);

Collections.sort(lists, new Comparator<Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
System.out.println("--------------------");
for (Map.Entry<String, Integer> entry : lists) {
System.out.println(entry.getKey() + " :: " + entry.getValue());
}
}
}

Output:

{p=5, q=0, r=9, s=8, v=8, z=2, o=0}
--------------------
q :: 0
o :: 0
z :: 2
p :: 5
s :: 8
v :: 8
r :: 9

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation