Java - Map

About

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

See Map

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.

Bidirectional

Snippets

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

// ......

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

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

Powered by ComboStrap