Java - Map

> Procedural Languages > Java

1 - About

Map is a data structure implementation of the java collection framework.

See Map

Advertising

3 - Implementation

  • hashmap. Permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
  • LinkedHashMap. A map implement with predictable iteration order. The order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map.
  • TreeMap. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. This implementation is not synchronized. If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.

4 - Snippets

4.1 - Initialization

// Object to string allowing all data type
Map<Object,String> myMapObjectString=new HashMap<Object, String>()
 
// String to string 
Map<String,String> myMapStringString=new HashMap<String, String>();
 
// ......

4.2 - Set

// Object to string allowing all data type
myMapObjectString.put(new Integer(1), "myStringValue1");
myMapObjectString.put(new Integer(2), "myStringValue2");
 
// String to string 
myMapStringString.put("myStringKey1","myStringValue1");
myMapStringString.put("myStringKey2","myStringValue2");

4.3 - Get

// Object to string allowing all data type
myMapObjectString.get(new Integer(1));
myMapObjectString.get(new Integer(2));
 
// String to string 
myMapStringString.get("myStringKey1");
myMapStringString.put("myStringKey2");

4.4 - Values to list

new ArrayList<>(map.values())

4.5 - Remove

myMap.remove(key);

4.6 - Iterate

HashMap<String,String> myHashMap = new HashMap<String,String>();
myHashMap.put("key1", "value1");
myHashMap.put("key2", "value2");
 
// For method
System.out.println("For Method");
for (Entry<String, String> entry : myHashMap.entrySet()) {
     System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
 
// Iterator Method
System.out.println("Iterator Method");
Iterator<Map.Entry<String,String>> iterator= myHashMap.entrySet().iterator();
while (iterator.hasNext())
{
      Map.Entry<String,String> entry  =iterator.next();   
      System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

4.7 - Equal

A map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal.

Advertising
lang/java/map.txt · Last modified: 2019/06/24 13:44 by gerardnico