1+ package com .hmkcode ;
2+
3+ import java .util .ArrayList ;
4+ import java .util .Comparator ;
5+ import java .util .HashMap ;
6+ import java .util .List ;
7+ import java .util .Map ;
8+ import java .util .Map .Entry ;
9+ import java .util .TreeMap ;
10+
11+
12+ import com .hmkcode .vo .Person ;
13+
14+
15+ public class MapApp
16+ {
17+
18+ public static void main ( String [] args )
19+ {
20+
21+
22+ // ( 1 ) Map
23+
24+ // A. Initiate
25+ Map <String ,Person > hashMap = new HashMap <String ,Person >();
26+ Map <String ,Person > treeMap = new TreeMap <String ,Person >();
27+
28+ // B. Populate
29+ int k = 0 ;
30+ for (Person person :getPersons ()){
31+ hashMap .put ("" +k ,person );
32+ treeMap .put ("" +k ++,person );
33+ }
34+
35+ // --> print
36+ System .out .println ("--------- Print All -------------" );
37+ System .out .println ("HashMap: " +hashMap );
38+ System .out .println ("TreeMap: " +treeMap );
39+
40+
41+ // C. Iterate
42+ // --> print
43+ System .out .println ("--------- Print Iterate by get(key) -------------" );
44+ for (String key :treeMap .keySet ()){
45+
46+ System .out .println ("treeMap: [key: " +key +" , value: " +treeMap .get (key ));
47+ }
48+ // --> print
49+ System .out .println ("--------- Print Iterate by Entry -------------" );
50+ for (Entry <String , Person > entry :treeMap .entrySet ()){
51+
52+ System .out .println ("treeMap: [key: " +entry .getKey ()+" , value: " +entry .getValue ());
53+ }
54+
55+ // D. Sort by value
56+ TreeMap <String ,Person > sorted_map = new TreeMap <String ,Person >(new ValueComparator ());
57+ sorted_map .putAll (hashMap );
58+
59+
60+ // --> print
61+ System .out .println ("--------- Print Sorted Map by Value -------------" );
62+ System .out .println ("Sorted HashMap: " +sorted_map );
63+
64+
65+ // E. Convert Map to List
66+
67+ List <Person > persons = new ArrayList <Person >(sorted_map .values ());
68+
69+ // --> print
70+ System .out .println ("--------- Print List<Person> -------------" );
71+ System .out .println ("List<Person>: " +persons );
72+ }
73+
74+ private static Person [] getPersons (){
75+ Person [] persons = new Person [5 ];
76+
77+ persons [0 ] = new Person ("Brit" , 29 );
78+ persons [1 ] = new Person ("John" , 32 );
79+ persons [2 ] = new Person ("Jack" , 27 );
80+ persons [3 ] = new Person ("Jenifer" , 24 );
81+ persons [4 ] = new Person ("Brit" , 37 );
82+
83+ return persons ;
84+ }
85+ }
86+ class ValueComparator implements Comparator {
87+
88+ Map map ;
89+
90+ public ValueComparator (){
91+
92+ }
93+ public int compare (Object keyA , Object keyB ){
94+
95+ return ((String ) keyA ).compareTo ((String ) keyB );
96+
97+ }
98+ }
0 commit comments