Java Tutorial/Collections/Map — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 08:04, 1 июня 2010
Содержание
- 1 A map declared to hold objects of a type T can also hold objects that extend from T
- 2 Automatically Removing an Unreferenced Element from a Hash Table
- 3 A value retrieved from a type-specific collection does not need to be casted
- 4 Convert Properties into Map
- 5 Create an array containing the keys in a map
- 6 Create an array containing the values in a map
- 7 Create type specific collections
- 8 Creating a Hash Table
- 9 Creating a Map That Retains Order-of-Insertion
- 10 Creating and storing arrays in a map
- 11 Creating a Type-Specific Map [5.0]
- 12 Creating a Type-Specific Map: creates a map whose keys are Integer objects and values are String objects.
- 13 Get a key from value with an HashMap
- 14 Map techniques.
- 15 Retrieve environment variables (JDK1.5)
- 16 Sort based on the values
A map declared to hold objects of a type T can also hold objects that extend from T
<source lang="java">
import java.util.HashMap; import java.util.Map; public class Main {
public static void main(String[] argv) { Map<Number, String> numMap = new HashMap<Number, String>(); numMap.put(.5, "half"); numMap.put(1, "first"); }
}</source>
Automatically Removing an Unreferenced Element from a Hash Table
<source lang="java">
import java.util.Iterator; import java.util.Map; import java.util.WeakHashMap; public class Main {
public static void main(String[] argv) throws Exception { Map weakMap = new WeakHashMap(); Object keyObject = ""; Object valueObject = ""; weakMap.put(keyObject, valueObject); Iterator it = weakMap.keySet().iterator(); while (it.hasNext()) { Object key = it.next(); } }
}</source>
A value retrieved from a type-specific collection does not need to be casted
<source lang="java">
import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; public class Main {
public static void main(String[] argv) { Map<String, URL> urlMap = new HashMap<String, URL>(); try { urlMap.put("java", new URL("http://www.jexp.ru")); } catch (MalformedURLException e) { } String s = urlMap.get("java").getHost(); }
}</source>
Convert Properties into Map
<source lang="java">
import java.util.Properties; import java.util.Map; import java.util.HashMap; import java.util.Set; public class Main {
public static void main(String[] args) { Properties properties = new Properties(); properties.setProperty("name", "Designer"); properties.setProperty("version", "1.0"); properties.setProperty("vendor", "Inc"); Map<String, String> map = new HashMap<String, String>((Map) properties); Set propertySet = map.entrySet(); for (Object o : propertySet) { Map.Entry entry = (Map.Entry) o; System.out.printf("%s = %s%n", entry.getKey(), entry.getValue()); } }
}</source>
Create an array containing the keys in a map
<source lang="java">
import java.util.HashMap; import java.util.Map; public class Main {
public static void main(String[] argv) throws Exception { Map map = new HashMap(); Object[] objectArray = map.keySet().toArray(); MyClass[] array = (MyClass[]) map.keySet().toArray(new MyClass[map.keySet().size()]); }
} class MyClass { }</source>
Create an array containing the values in a map
<source lang="java">
import java.util.HashMap; import java.util.Map; public class Main {
public static void main(String[] argv) throws Exception { Map map = new HashMap(); Object[] objectArray = map.values().toArray(); MyClass[] array = (MyClass[]) map.values().toArray(new MyClass[map.values().size()]); }
} class MyClass { }</source>
Create type specific collections
<source lang="java">
import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ArrayList; public class Main {
public static void main(String[] args) { Map<Integer, String> grades = new HashMap<Integer, String>(); grades.put(1, "A"); grades.put(2, "B"); grades.put(3, "C"); grades.put(4, "D"); grades.put(5, "E"); String value = grades.get(1); List<String> dayNames = new ArrayList<String>(); dayNames.add("Sunday"); dayNames.add("Monday"); dayNames.add("Tuesday"); dayNames.add("Wednesday"); String firstDay = dayNames.get(0); }
}</source>
Creating a Hash Table
<source lang="java">
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; public class Main {
public static void main(String[] argv) throws Exception { Map<String, Integer> map = new HashMap<String, Integer>(); map = new TreeMap(); map.put("a", new Integer(1)); map.put("b", new Integer(2)); map.put("c", new Integer(3)); int size = map.size(); // 2 Object oldValue = map.put("a", new Integer(9)); // 1 oldValue = map.remove("c"); // 3 Iterator it = map.keySet().iterator(); while (it.hasNext()) { Object key = it.next(); } it = map.values().iterator(); while (it.hasNext()) { Object value = it.next(); } }
}</source>
Creating a Map That Retains Order-of-Insertion
<source lang="java">
import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; public class Main {
public static void main(String[] argv) throws Exception { Map<String, String> map = new LinkedHashMap<String, String>(); map.put("1", "value1"); map.put("2", "value2"); map.put("3", "value3"); map.put("2", "value4"); for (Iterator it = map.keySet().iterator(); it.hasNext();) { Object key = it.next(); Object value = map.get(key); } }
}</source>
Creating and storing arrays in a map
<source lang="java">
import java.util.Iterator; import java.util.Map; import java.util.TreeMap; public class Main {
public static void main(String[] args) { Map<String, int[]> map = new TreeMap<String, int[]>(); int[] array = new int[3]; array[0] = 0; array[1] = 1; array[2] = 2; map.put("array", array); Iterator<String> iter = map.keySet().iterator(); while (iter.hasNext()) { String arrayName = iter.next(); array = map.get(arrayName); System.out.print(arrayName + ":"); for (int i = 0; i < array.length; i++) { System.out.print(array[i]); } } }
} //array:012</source>
Creating a Type-Specific Map [5.0]
<source lang="java">
import java.util.HashMap; import java.util.Map; public class Main {
public static void main(String[] argv) throws Exception { Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, "first"); map.put(2, "second"); // map.put(1, 2); <- Syntax error }
}</source>
Creating a Type-Specific Map: creates a map whose keys are Integer objects and values are String objects.
<source lang="java">
import java.util.HashMap; import java.util.Map; public class Main {
public static void main(String[] argv) { Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, "first"); map.put(2, "second"); // map.put(1, 2); <- Syntax error }
}</source>
Get a key from value with an HashMap
<source lang="java">
import java.util.HashMap; import java.util.Map; public class Main {
public static void main(String[] argv) { Map<String, String> map = new HashMap<String, String>(); map.put("1","one"); map.put("2","two"); map.put("3","three"); map.put("4","four"); System.out.println(getKeyFromValue(map,"three")); } public static Object getKeyFromValue(Map hm, Object value) { for (Object o : hm.keySet()) { if (hm.get(o).equals(value)) { return o; } } return null; }
}</source>
Map techniques.
<source lang="java">
import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class Main {
public static void main(String args[]) { Map<String, Integer> atomNums = new TreeMap<String, Integer>(); atomNums.put("A", 1); atomNums.put("B", 2); atomNums.put("C", 3); atomNums.put("D", 4); atomNums.put("E", 5); atomNums.put("F", 6); System.out.println("The map contains these " + atomNums.size() + " entries:"); Set<Map.Entry<String, Integer>> set = atomNums.entrySet(); for (Map.Entry<String, Integer> me : set) { System.out.print(me.getKey() + ", Atomic Number: "); System.out.println(me.getValue()); } TreeMap<String, Integer> atomNums2 = new TreeMap<String, Integer>(); atomNums2.put("Q", 30); atomNums2.put("W", 82); atomNums.putAll(atomNums2); set = atomNums.entrySet(); System.out.println("The map now contains these " + atomNums.size() + " entries:"); for (Map.Entry<String, Integer> me : set) { System.out.print(me.getKey() + ", Atomic Number: "); System.out.println(me.getValue()); } if (atomNums.containsKey("A")) System.out.println("A has an atomic number of " + atomNums.get("A")); if (atomNums.containsValue(82)) System.out.println("The atomic number 82 is in the map."); System.out.println(); if (atomNums.remove("A") != null) System.out.println("A has been removed.\n"); else System.out.println("Entry not found.\n"); Set<String> keys = atomNums.keySet(); for (String str : keys) System.out.println(str + " "); Collection<Integer> vals = atomNums.values(); for (Integer n : vals) System.out.println(n + " "); atomNums.clear(); if (atomNums.isEmpty()) System.out.println("The map is now empty."); }
}</source>
Retrieve environment variables (JDK1.5)
<source lang="java">
import java.util.Iterator; import java.util.Map; public class Main {
public static void main(String args[]) { System.out.println("PATH = " + System.getenv("PATH")); Map env = System.getenv(); for (Iterator it = env.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); System.out.println(entry.getKey() + " = " + entry.getValue()); } }
}</source>
Sort based on the values
<source lang="java">
import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; public class Main {
public static void main(String[] a) { Map<String, String> yourMap = new HashMap<String, String>(); yourMap.put("1", "one"); yourMap.put("2", "two"); yourMap.put("3", "three"); Map<String, Object> map = new LinkedHashMap<String, Object>(); List<String> keyList = new ArrayList<String>(yourMap.keySet()); List<String> valueList = new ArrayList<String>(yourMap.values()); Set<String> sortedSet = new TreeSet<String>(valueList); Object[] sortedArray = sortedSet.toArray(); int size = sortedArray.length; for (int i = 0; i < size; i++) { map.put(keyList.get(valueList.indexOf(sortedArray[i])), sortedArray[i]); } Set ref = map.keySet(); Iterator it = ref.iterator(); while (it.hasNext()) { String i = (String) it.next(); System.out.println(i); } }
}</source>