map interface in java code example
Example 1: create map java
Map<String, Integer> map = new HashMap<>();
Example 2: map java
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Map<Integer, String> hm = new HashMap<>();
hm.put(10, "1");
hm.put(20, "2");
hm.put(30, "3");
hm.put(40, "4");
hm.put(50, "5");
hm.put(50, "6");
System.out.println("Parcours de l'objet HashMap : ");
Set<Entry<Integer, String>> setHm = hm.entrySet();
Iterator<Entry<Integer, String>> it = setHm.iterator();
while(it.hasNext()){
Entry<Integer, String> e = it.next();
System.out.println(e.getKey() + " : " + e.getValue());
}
System.out.println("Valeur pour la clé 8 : " + hm.get(8));
Map<Integer, String> lhm = new LinkedHashMap<>();
lhm.put(10, "1");
lhm.put(20, "2");
lhm.put(30, "3");
lhm.put(40, "4");
lhm.put(50, "5");
System.out.println("Parcours de l'objet LinkedHashMap : ");
Set<Entry<Integer, String>> setLhm = lhm.entrySet();
Iterator<Entry<Integer, String>> it2 = setLhm.iterator();
while(it2.hasNext()){
Entry<Integer, String> e = it2.next();
System.out.println(e.getKey() + " : " + e.getValue());
}
}
}
Example 3: map in java
MAP : is a (key-value format)
and keys are always unique,
and value can be duplicated.
- HashTable don't have null key, sychronized(thread-safe)
- LinkedHashMap can have null key, keeps order
- HasHMap can have null key, order is not guaranteed
- TreeMap doesn't have null key and keys are sorted
Example 4: java map declaration
Map< String,Integer> hm =
new HashMap< String,Integer>();
hm.put("a", new Integer(100));
hm.put("b", new Integer(200));
hm.put("c", new Integer(300));
hm.put("d", new Integer(400));