Table of Contents

Java - Map

About

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

See Map

Implementation

Bidirectional

Snippets

Initialization

from Maps

Maps.of(1, 2, ...)

from Object

// 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>();

// ......

from Stream

Stream

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));

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");

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");

Sort

In a stream, by key

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

Values

Values to list

new ArrayList<>(map.values())

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);

Remove

myMap.remove(key);

Iterate

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());
}

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));

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.

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();

Compute

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

How to

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();
}

GroupBy with stream

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