1Map<String, String> map = new HashMap<>();
2
3for(Entry<String, String> entry:map.entrySet()) {
4 System.out.println("key: "+entry.getKey()+" value: "+entry.getValue());
5}
1
2MAP : is a (key-value format)
3 and keys are always unique,
4 and value can be duplicated.
5- HashTable don't have null key, sychronized(thread-safe)
6- LinkedHashMap can have null key, keeps order
7- HasHMap can have null key, order is not guaranteed
8- TreeMap doesn't have null key and keys are sorted
1import java.util.HashMap;
2import java.util.Iterator;
3import java.util.LinkedHashMap;
4import java.util.Map;
5import java.util.Map.Entry;
6import java.util.Set;
7
8
9public class Main {
10 public static void main(String[] args) {
11
12 //La fameuse syntaxe en diamant de Java 7
13 Map<Integer, String> hm = new HashMap<>();
14 hm.put(10, "1");
15 hm.put(20, "2");
16 hm.put(30, "3");
17 hm.put(40, "4");
18 hm.put(50, "5");
19 //Ceci va écraser la valeur 5
20 hm.put(50, "6");
21
22 System.out.println("Parcours de l'objet HashMap : ");
23 Set<Entry<Integer, String>> setHm = hm.entrySet();
24 Iterator<Entry<Integer, String>> it = setHm.iterator();
25 while(it.hasNext()){
26 Entry<Integer, String> e = it.next();
27 System.out.println(e.getKey() + " : " + e.getValue());
28 }
29
30 System.out.println("Valeur pour la clé 8 : " + hm.get(8));
31
32 Map<Integer, String> lhm = new LinkedHashMap<>();
33 lhm.put(10, "1");
34 lhm.put(20, "2");
35 lhm.put(30, "3");
36 lhm.put(40, "4");
37 lhm.put(50, "5");
38
39 System.out.println("Parcours de l'objet LinkedHashMap : ");
40 Set<Entry<Integer, String>> setLhm = lhm.entrySet();
41 Iterator<Entry<Integer, String>> it2 = setLhm.iterator();
42 while(it2.hasNext()){
43 Entry<Integer, String> e = it2.next();
44 System.out.println(e.getKey() + " : " + e.getValue());
45 }
46 }
47}
48
1Map< String,Integer> hm =
2 new HashMap< String,Integer>();
3 hm.put("a", new Integer(100));
4 hm.put("b", new Integer(200));
5 hm.put("c", new Integer(300));
6 hm.put("d", new Integer(400));