GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — Java/java-list-map/src/main/java/com/hmkcode/MapApp.java at master · Itinganet/Java Expand file tree/ Copy pathMapApp.javaMore file actions 98 lines (68 loc) · 2.61 KB / Copy pathMapApp.javaFile metadata and controls98 lines (68 loc) · 2.61 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 package com.hmkcode; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import com.hmkcode.vo.Person; public class MapApp { public static void main( String[] args ) { // ( 1 ) Map // A. Initiate Map<String,Person> hashMap = new HashMap<String,Person>(); Map<String,Person> treeMap = new TreeMap<String,Person>(); // B. Populate int k = 0 ; for(Person person:getPersons()){ hashMap.put(""+k,person); treeMap.put(""+k++,person); } // --> print System.out.println("--------- Print All -------------"); System.out.println("HashMap: "+hashMap); System.out.println("TreeMap: "+treeMap); // C. Iterate // --> print System.out.println("--------- Print Iterate by get(key) -------------"); for(String key:treeMap.keySet()){ System.out.println("treeMap: [key: "+key+" , value: "+treeMap.get(key)); } // --> print System.out.println("--------- Print Iterate by Entry -------------"); for(Entry<String, Person> entry:treeMap.entrySet()){ System.out.println("treeMap: [key: "+entry.getKey()+" , value: "+entry.getValue()); } // D. Sort by value TreeMap<String,Person> sorted_map = new TreeMap<String,Person>(new ValueComparator()); sorted_map.putAll(hashMap); // --> print System.out.println("--------- Print Sorted Map by Value -------------"); System.out.println("Sorted HashMap: "+sorted_map); // E. Convert Map to List List<Person> persons = new ArrayList<Person>(sorted_map.values()); // --> print System.out.println("--------- Print List<Person> -------------"); System.out.println("List<Person>: "+persons); } private static Person[] getPersons(){ Person[] persons = new Person[5]; persons[0] = new Person("Brit", 29); persons[1] = new Person("John", 32); persons[2] = new Person("Jack", 27); persons[3] = new Person("Jenifer", 24); persons[4] = new Person("Brit", 37); return persons; } } class ValueComparator implements Comparator { Map map; public ValueComparator(){ } public int compare(Object keyA, Object keyB){ return ((String) keyA).compareTo((String) keyB); } } |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |