Java - Map

1 - About

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

See Map

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.

3.1 - Bidirectional

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.1.1 - from Stream

Java - Stream Processing

  • How to create a custom map implementation ? MapBiDirectional is a custom implementation

MapBiDirectional biMap = columns
    .stream()
    .collect(Collectors.toMap(
        ColumnDef::getColumnPosition, // the key
        ColumnDef::getColumnPosition, // the value
        (e1, e2) -> e1, // the merge resolution 
        MapBiDirectional::new // the provider
        ));

or


System.getenv().entrySet()
      .stream()
      .filter(e->e.getKey().startsWith("path"))
      .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

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 - Sort

In a stream, by key


.sorted(Comparator.comparing(Map.Entry::getKey))

4.5 - Values

4.5.1 - Values to list


new ArrayList<>(map.values())

4.5.2 - Values to sorted array

A collection of column object in the values sorted will be sorted and returned as an array


(new ArrayList<>(map.values()))
      .stream()
      .sorted()
      .toArray(Column[]::new);

4.6 - Remove


myMap.remove(key);

4.7 - Iterate

4.7.1 - for / while


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.2 - Stream

All environment configuration that starts with path


System.getenv().entrySet()
      .stream()
      .filter(e->e.getKey().startsWith("path"))
      .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

4.8 - 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.

4.9 - Immutable


import com.google.common.collect.ImmutableMap;
private static final Map<Type, String> SQL_TYPES = ImmutableMap.<Type, String>builder()
            .put(BOOLEAN, "boolean")
            .put(BIGINT, "bigint")
            .put(INTEGER, "integer")
            .put(SMALLINT, "smallint")
            .put(TINYINT, "tinyint")
            .put(DOUBLE, "double precision")
            .put(REAL, "real")
            .put(VARBINARY, "varbinary")
            .put(DATE, "date")
            .put(TIME, "time")
            .put(TIME_WITH_TIME_ZONE, "time with timezone")
            .put(TIMESTAMP, "timestamp")
            .put(TIMESTAMP_WITH_TIME_ZONE, "timestamp with timezone")
            .build();

4.10 - Compute


Map<String, List<String>> map = new HashMap<>();
List<String> values = map.computeIfAbsent("key", k -> new ArrayList<>());

5 - How to

5.1 - Implement a frequency counter (histogram)

How to implement a scalable frequency map (a form of histogram or multiset)


ConcurrentHashMap<String,LongAdder> freqs = new HashMap<>();
freqs.computeIfAbsent(k -> new LongAdder()).increment();


List<Object> objects = Arrays.asList(1,2,1,3,4);
Map<Object,AtomicLong> datas = new HashMap<>();
for(Object object: objects){
    datas.computeIfAbsent(key,k->new AtomicLong(0)).incrementAndGet();
}

5.2 - GroupBy with stream


Map<City, Set<Person>> mapCityPerson = persons
        .stream()
        .collect(
          Colletors.groupingBy(
            Person::getCity,
            Collectors.mapping(e -> e, toSet()))
        );


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap