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 index fe0aab9218..6bf56274ac 100644 --- a/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java +++ b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java @@ -2,9 +2,7 @@ package com.baeldung.sort; import com.baeldung.performance.Employee; -import java.util.HashMap; -import java.util.Map; -import java.util.TreeMap; +import java.util.*; public class SortHashMap { @@ -14,11 +12,28 @@ public class SortHashMap { initialize(); - treeMapSortByKey(); + //treeMapSortByKey(); + + //arrayListSortByValue(); + //arrayListSortByKey(); + + treeSetByKey(); + treeSetByValue(); } - public static void treeMapSortByKey() - { + private static void treeSetByValue() { + Comparator comp = (Employee o1, Employee o2) -> (o1.getId().compareTo(o2.getId())); + SortedSet values = new TreeSet<>(comp); + values.addAll(map.values()); + System.out.println(values); + } + + private static void treeSetByKey() { + SortedSet keys = new TreeSet<>(map.keySet()); + System.out.println(keys); + } + + private static void treeMapSortByKey() { TreeMap sorted = new TreeMap<>(map); sorted.putAll(map); @@ -29,6 +44,25 @@ public class SortHashMap { } + private static void arrayListSortByValue() { + List employeeById = new ArrayList<>(map.values()); + + Collections.sort(employeeById, new Comparator() { + + public int compare(Employee o1, Employee o2) { + return (int)(o1.getId() - o2.getId()); + } + }); + + System.out.println(employeeById); + } + + private static void arrayListSortByKey() { + List employeeByKey = new ArrayList<>(map.keySet()); + Collections.sort(employeeByKey); + System.out.println(employeeByKey); + } + private static void initialize() { Employee employee1 = new Employee(1L, "Mher"); map.put(employee1.getName(), employee1);