diff --git a/core-java-collections/src/main/java/com/baeldung/performance/Employee.java b/core-java-collections/src/main/java/com/baeldung/performance/Employee.java index d811cfbb7d..1ed4410371 100644 --- a/core-java-collections/src/main/java/com/baeldung/performance/Employee.java +++ b/core-java-collections/src/main/java/com/baeldung/performance/Employee.java @@ -44,4 +44,12 @@ public class Employee { result = 31 * result + name.hashCode(); return result; } + + @Override + public String toString() { + return "Employee{" + + "id=" + id + + ", name='" + name + '\'' + + '}'; + } } diff --git a/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java new file mode 100644 index 0000000000..fe0aab9218 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java @@ -0,0 +1,42 @@ +package com.baeldung.sort; + +import com.baeldung.performance.Employee; + +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; + +public class SortHashMap { + + private static Map map = new HashMap<>(); + + public static void main(String[] args) { + + initialize(); + + treeMapSortByKey(); + } + + public static void treeMapSortByKey() + { + TreeMap sorted = new TreeMap<>(map); + sorted.putAll(map); + + for (Map.Entry entry : sorted.entrySet()) { + System.out.println("Key = " + entry.getKey() + + ", Value = " + entry.getValue()); + } + + } + + private static void initialize() { + Employee employee1 = new Employee(1L, "Mher"); + map.put(employee1.getName(), employee1); + Employee employee2 = new Employee(22L, "Annie"); + map.put(employee2.getName(), employee2); + Employee employee3 = new Employee(8L, "John"); + map.put(employee3.getName(), employee3); + Employee employee4 = new Employee(2L, "George"); + map.put(employee4.getName(), employee4); + } +}