22
33import com .baeldung .performance .Employee ;
44
5- import java .util .HashMap ;
6- import java .util .Map ;
7- import java .util .TreeMap ;
5+ import java .util .*;
86
97public class SortHashMap {
108
@@ -14,11 +12,28 @@ public static void main(String[] args) {
1412
1513 initialize ();
1614
17- treeMapSortByKey ();
15+ //treeMapSortByKey();
16+
17+ //arrayListSortByValue();
18+ //arrayListSortByKey();
19+
20+ treeSetByKey ();
21+ treeSetByValue ();
22+ }
23+
24+ private static void treeSetByValue () {
25+ Comparator <Employee > comp = (Employee o1 , Employee o2 ) -> (o1 .getId ().compareTo (o2 .getId ()));
26+ SortedSet <Employee > values = new TreeSet <>(comp );
27+ values .addAll (map .values ());
28+ System .out .println (values );
1829 }
1930
20- public static void treeMapSortByKey ()
21- {
31+ private static void treeSetByKey () {
32+ SortedSet <String > keys = new TreeSet <>(map .keySet ());
33+ System .out .println (keys );
34+ }
35+
36+ private static void treeMapSortByKey () {
2237 TreeMap <String , Employee > sorted = new TreeMap <>(map );
2338 sorted .putAll (map );
2439
@@ -29,6 +44,25 @@ public static void treeMapSortByKey()
2944
3045 }
3146
47+ private static void arrayListSortByValue () {
48+ List <Employee > employeeById = new ArrayList <>(map .values ());
49+
50+ Collections .sort (employeeById , new Comparator <Employee >() {
51+
52+ public int compare (Employee o1 , Employee o2 ) {
53+ return (int )(o1 .getId () - o2 .getId ());
54+ }
55+ });
56+
57+ System .out .println (employeeById );
58+ }
59+
60+ private static void arrayListSortByKey () {
61+ List <String > employeeByKey = new ArrayList <>(map .keySet ());
62+ Collections .sort (employeeByKey );
63+ System .out .println (employeeByKey );
64+ }
65+
3266 private static void initialize () {
3367 Employee employee1 = new Employee (1L , "Mher" );
3468 map .put (employee1 .getName (), employee1 );
0 commit comments