Vous êtes sur la page 1sur 2

TreeMapExample.

java

1 import java.util.Map;
3
4 /*
5 * TreeMap official documentation:
6 * https://goo.gl/XFPD1a
7 */
8
9 public class TreeMapExample {
10
11 public static void main(String[] args) {
12 // Declare a TreeMap, where the key is string, and the value is integer
13 TreeMap<String, Integer> map = new TreeMap<>();
14
15 // Associates the specified value with the specified key in this map.
16 map.put("Husam", 123456);
17 map.put("Ibraheem", 7896);
18 map.put("Alaa", 99999);
19 map.put("Mohammad", 7896);
20 map.put("Hamza", 776);
21 map.put("Motasem", 11);
22
23 // Returns the number of key-value mappings in this map.
24 System.out.println(map.size() + "\n");
25
26 /*
27 * Returns a key-value mapping associated with the least key in this map, or
28 * null if the map is empty.
29 */
30 Map.Entry<String, Integer> entry = map.firstEntry();
31 System.out.println(entry.getKey() + " --> " + entry.getValue());
32
33 // Returns the first (lowest) key currently in this map.
34 System.out.println("First element --> " + map.firstKey() + "\n");
35
36 /*
37 * Returns the value to which the specified key is mapped, or null if this
map
38 * contains no mapping for the key.
39 */
40 System.out.println("Husam --> " + map.get("Husam") + "\n");
41 System.out.println("HuSam --> " + map.get("HuSam") + "\n");
42
43 // Returns true if this map contains a mapping for the specified key.
44 if (map.containsKey("Ibraheem"))
45 System.out.println("Ibraheem --> YES\n");
46 else
47 System.out.println("Ibraheem --> NO\n");
48 if (map.containsKey("Ahmad"))
49 System.out.println("Ahmad --> YES\n");
50 else
51 System.out.println("Ahmad--> NO\n");
52
53 // Returns true if this map maps one or more keys to the specified value.
54 if (map.containsValue(123456))
55 System.out.println("123456 --> YES\n");
56 else
57 System.out.println("123456 --> NO\n");
58 if (map.containsValue(88))
59 System.out.println("88 --> YES\n");
60 else
61 System.out.println("88--> NO\n");
62
63 // Iterate over the TreeMap and print all values
64 for (Map.Entry<String, Integer> entry1 : map.entrySet(): map.entrySet()) {
65 String key = entry1.getKey();

Page 1
TreeMapExample.java

66 int value = entry1.getValue();


67 System.out.println(key + " => " + value);
68 // System.out.println(entry.getKey() + " => " + entry.getValue());
69 }
70 System.out.println();
71
72 // Removes all of the mappings from this map.
73 map.clear();
74 }
75 }
76

Page 2

Vous aimerez peut-être aussi