Hello sekitaka.
When I thought that I wanted to sort by the HashMap key, there was a TreeMap, which was convenient, so I will introduce it. TreeMap is a map with no duplicate keys like HashMap. In addition to that, sorting by key is done automatically.
TreeMap<String,String> treeMap = new TreeMap<>();
treeMap.put("2","2");
treeMap.put("b","B");
treeMap.put("1","1");
treeMap.put("a","A");
treeMap.put("1","1(Second time)");
System.out.println(treeMap);
The following result is output.
{1=1(Second time), 2=2, a=A, b=B}
Sorted by key as expected, eliminating duplicate keys.
The default sort order is Java's natural ordering, but you can also specify your own sort logic by specifying Comparator in the constructor as shown below.
TreeMap<String,String> treeMap = new TreeMap<>(new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
// [Abbreviation]Custom sort logic
}
});
What did you think. Java has a lot of standard libraries, so you can find various useful classes by searching.
Recommended Posts