Example 1: java hashmap syntax
import java.util.HashMap;
HashMap<String, String> capitalCities = new HashMap<String, String>();
capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC");
System.out.println(capitalCities);
Map<String, Integer> stGrade = new HashMap<String, Integer>();
stGrade.put("aaron", new Integer(90));
stGrade.put("isaac", new Integer(100));
stGrade.put("john", new Integer(35));
stGrade.put("mohammad", new Integer(100));
stGrade.get("mohammad");
stGrade.get("aaron");
stGrade.get("john");
stGrade.get("isaac");
Example 2: hashmaps java
import java.util.HashMap;
HashMap<Int, String> examplehashmap=new HashMap<>();
{
examplehashmap.put(5, "example");
};
examplehashmap.get(5);
Example 3: java hashmap example
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));
Example 4: 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 5: 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 6: 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));