Saturday, April 28, 2018

Sort a HashMap by key !!

Sorting a HashMap by key 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 SortMapByKey {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("z", 1);
map.put("q", 2);
map.put("p", 3);
map.put("s", 4);
map.put("o", 5);
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.getKey()).compareTo(o2.getKey());
}
});
System.out.println("--------------------");
for (Map.Entry<String, Integer> entry : lists) {
System.out.println(entry.getKey() + " :: " + entry.getValue());
}
}
}

Output: 
{p=3, q=2, s=4, z=1, o=5}
--------------------
o :: 5
p :: 3
q :: 2
s :: 4
z :: 1

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...