Duplicate Map sorted by key in Java

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.

How to use

TreeMap<String,String> treeMap = new TreeMap<>();
treeMap.put("1","1(Second time)");

The following result is output.

{1=1(Second time), 2=2, a=A, b=B}

Sorted by key as expected, eliminating duplicate keys.

Custom sort

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>(){
    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

Duplicate Map sorted by key in Java
Reverse Key from Value in Java Map
Sort Map values in ascending key order in Java TreeMap
[Java] How to get the key and value stored in Map by iterative processing
Get Null-safe Map values in Java
Use composite keys in Java Map.
JAVA (Map)
Key points for introducing gRPC in Java
Map without using an array in java
[Java] for Each and sorted in Lambda
Partization in Java
Changes in Java 11
[Java] Be careful of the key type of Map
Rock-paper-scissors in Java
[Java] Map comparison
[Java] Judgment by entering characters in the terminal
Pi in Java
FizzBuzz in Java
Replacing system environment variables by reflection in java
Read the packet capture obtained by tcpdump in Java
[JAVA] [Spring] [MyBatis] Use GROUP BY in SQL Builder
[memo] Generate RSA key pair for SSH in Java
[java] sort in list
Read JSON in Java
Interpreter implementation in Java
Make Blackjack in Java
Rock-paper-scissors app in Java
Constraint programming in Java
Put java8 in centos7
NVL-ish guy in Java
Combine arrays in Java
"Hello World" in Java
Callable Interface in Java
Comments in Java source
[Java] Stream API / map
Azure functions in java
Format XML in Java
Simple htmlspecialchars in Java
Boyer-Moore implementation in Java
Hello World in Java
Use OpenCV in Java
Enum reverse map Java
webApi memorandum in java
Type determination in Java
Ping commands in Java
Various threads in java
Heapsort implementation (in java)
Zabbix API in Java
Java bidirectional map library
ASCII art in Java
Compare Lists in Java
Express failure in Java
Create JSON in Java
Date manipulation in Java 8
What's new in Java 8
Use PreparedStatement in Java
What's new in Java 9,10,11
Parallel execution in Java
Initializing HashMap in Java
Update your Java knowledge by writing a gRPC server in Java (2)