Skip to content
Related Articles

Related Articles

Improve Article

ConcurrentSkipListMap in Java with Examples

  • Difficulty Level : Expert
  • Last Updated : 24 Nov, 2020

The ConcurrentSkipListMap class is a member of the Java Collections Framework. It was introduced in JDK 1.6, it belongs to java.util.concurrent package. The ConcurrentSkipListMap is a scalable implementation of ConcurrentNavigableMap. All the elements are sorted based on natural ordering or by the Comparator passed during it’s construction time. This class uses a concurrent variation of SkipList data structure providing log(n) time cost for insertion, removal, update, and access operations. These operations are safe for executing concurrently by multiple threads. 

Declaration

public class ConcurrentSkipListMap<K,​V> extends AbstractMap<K,​V> implements ConcurrentNavigableMap<K,​V>, Cloneable, Serializable

Here, K is the key Object type and V is the value Object type.

The Hierarchy of ConcurrentSkipListMap



ConcurrentSkipListMap-in-Java-with-Examples

It implements Serializable, Cloneable, ConcurrentMap<K,​V>, ConcurrentNavigableMap<K,​V>, Map<K,​V>, NavigableMap<K,​V>, SortedMap<K,​V> interfaces and extends AbstractMap<K, V> class.

Constructors of ConcurrentSkipListMap

1. ConcurrentSkipListMap(): Constructs a new, empty map, sorted according to the natural ordering of the keys.

ConcurrentSkipListMap<K, V> cslm = new ConcurrentSkipListMap<K, V>();

2. ConcurrentSkipListMap​(Comparator<? super K> comparator): Constructs a new, empty map, sorted according to the specified comparator.

ConcurrentSkipListMap<K, V> cslm = new ConcurrentSkipListMap​<K, V>(Comparator<? super K> comparator);

3. ConcurrentSkipListMap​(Map<? extends K,​? extends V> m): Constructs a new map containing the same mappings as the given map, sorted according to the natural ordering of the keys.​

ConcurrentSkipListMap<K, V> cslm = new ConcurrentSkipListMap<K, V>​(Map<? extends K,​? extends V> m);



4. ConcurrentSkipListMap​(SortedMap<K,​? extends V> m): Constructs a new map containing the same mappings and using the same ordering as the specified sorted map.

ConcurrentSkipListMap​<K, V> cslm = new ConcurrentSkipListMap​<K, V>(SortedMap<K,​? extends V> m);

Example

Java




// Java Program to Demonstrate
// ConcurrentSkipListMap
  
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
  
class ConcurrentSkipListMapExample {
    public static void main(String[] args)
    {
        // create an instance of ConcurrentSkipListMap
        ConcurrentSkipListMap<String, String> cslm
            = new ConcurrentSkipListMap<String, String>();
  
        // Add mappings using put method
        cslm.put("3", "Geeks");
        cslm.put("2", "from");
        cslm.put("1", "Hi!");
        cslm.put("5", "Geeks");
        cslm.put("4", "for");
  
        // print to the console
        System.out.println("Initial Map : " + cslm);
  
        // print key-value pair whose key is greater than 2
        System.out.println("ceilingEntry-2: "
                           + cslm.ceilingEntry("2"));
  
        // get the descending key set
        NavigableSet navigableSet = cslm.descendingKeySet();
  
        System.out.println("descendingKeySet: ");
  
        // Iterate through the keySet
        Iterator itr = navigableSet.iterator();
        while (itr.hasNext()) {
            String s = (String)itr.next();
            System.out.println(s);
        }
  
        // print the first mapping
        System.out.println("firstEntry: "
                           + cslm.firstEntry());
  
        // print the last mapping
        System.out.println("lastEntry: "
                           + cslm.lastEntry());
  
        // remove the first mapping and print it
        System.out.println("pollFirstEntry: "
                           + cslm.pollFirstEntry());
  
        // print the first mapping
        System.out.println("now firstEntry: "
                           + cslm.firstEntry());
  
        // remove the last mapping and print it
        System.out.println("pollLastEntry: "
                           + cslm.pollLastEntry());
  
        // print the last mapping
        System.out.println("now lastEntry: "
                           + cslm.lastEntry());
    }
}
Output
Initial Map : {1=Hi!, 2=from, 3=Geeks, 4=for, 5=Geeks}
ceilingEntry-2: 2=from
descendingKeySet: 
5
4
3
2
1
firstEntry: 1=Hi!
lastEntry: 5=Geeks
pollFirstEntry: 1=Hi!
now firstEntry: 2=from
pollLastEntry: 5=Geeks
now lastEntry: 4=for

Basic Operations

1. Add Mappings

The put() method of ConcurrentSkipListMap associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

Java




// Java Program to demonstrate adding
// mappings to a ConcurrentSkipListMap
  
import java.util.concurrent.*;
  
class AddingMappingsExample {
    public static void main(String[] args)
    {
  
        // Initializing the map
        ConcurrentSkipListMap<Integer, Integer> cslm
            = new ConcurrentSkipListMap<Integer, Integer>();
  
        // Adding elements to this map
        for (int i = 1; i <= 9; i++)
            cslm.put(i, i);
  
        // put() operation on the map
        System.out.println("After put(): " + cslm);
    }
}
Output
After put(): {1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9}

2. Remove Mappings

The remove() method of ConcurrentSkipListMap removes the mapping for the specified key from this map. The method returns null if there is no mapping for of that particular key. After this method is performed the size of the map is reduced. To remove the first entry and last entry of the map, we can use pollFirstEntry() and pollLastEntry() respectively.

Java




// Java Program Demonstrate removing
// mappings from ConcurrentSkipListMap
  
import java.util.concurrent.*;
  
class RemovingMappingsExample {
    public static void main(String[] args)
    {
  
        // Initializing the map
        ConcurrentSkipListMap<Integer, Integer> cslm
            = new ConcurrentSkipListMap<Integer, Integer>();
  
        // Adding elements to this map
        for (int i = 1; i <= 6; i++)
            cslm.put(i, i);
  
        // remove() operation on the map
        cslm.remove(5);
  
        // print the modified map
        System.out.println("After remove(): " + cslm);
  
        // remove the first mapping and print it
        System.out.println("pollFirstEntry: "
                           + cslm.pollFirstEntry());
  
        // remove the last mapping and print it
        System.out.println("pollLastEntry: "
                           + cslm.pollLastEntry());
            
          // Print final map
          System.out.println("map contents: " + cslm);
    }
}
Output



After remove(): {1=1, 2=2, 3=3, 4=4, 6=6}
pollFirstEntry: 1=1
pollLastEntry: 6=6
map contents: {2=2, 3=3, 4=4}

 3. Iterating

We can use the Iterator interface to traverse over any structure of the Collection Framework. Since Iterators work with one type of data we use Entry< ? , ? > to resolve the two separate types into a compatible format. Then using the next() method we print the elements of the ConcurrentSkipListMap.

Java




// Java Program to demonstrate iterating
// over ConcurrentSkipListMap
  
import java.util.concurrent.*;
import java.util.*;
  
class IteratingExample {
    public static void main(String[] args)
    {
        // create an instance of ConcurrentSkipListMap
        ConcurrentSkipListMap<Integer, Integer> cslm
            = new ConcurrentSkipListMap<>();
  
        // Add mappings using put method
        for (int i = 0; i < 6; i++) {
            cslm.put(i, i);
        }
  
        // Create an Iterator over the
        // ConcurrentSkipListMap
        Iterator<ConcurrentSkipListMap
                     .Entry<Integer, Integer> > itr
            = cslm.entrySet().iterator();
  
        // The hasNext() method is used to check if there is
        // a next element The next() method is used to
        // retrieve the next element
        while (itr.hasNext()) {
            ConcurrentSkipListMap
                .Entry<Integer, Integer> entry
                = itr.next();
            System.out.println("Key = " + entry.getKey()
                               + ", Value = "
                               + entry.getValue());
        }
    }
}
Output
Key = 0, Value = 0
Key = 1, Value = 1
Key = 2, Value = 2
Key = 3, Value = 3
Key = 4, Value = 4
Key = 5, Value = 5

Methods of ConcurrentSkipListMap

METHOD

DESCRIPTION

ceilingEntry​(K key)Returns a key-value mapping associated with the least key greater than or equal to the given key, or null if there is no such entry.
ceilingKey​(K key)Returns the least key greater than or equal to the given key, or null if there is no such key.
clear()Removes all of the mappings from this map.
clone()Returns a shallow copy of this ConcurrentSkipListMap instance.
compute​(K key, BiFunction<? super K,​? super V,​? extends V> remappingFunction)Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
computeIfAbsent​(K key, Function<? super K,​? extends V> mappingFunction)If the specified key is not already associated with a value, attempts to compute its value using the given mapping function and enters it into this map unless null.
computeIfPresent​(K key, BiFunction<? super K,​? super V,​? extends V> remappingFunction)If the value for the specified key is present, attempts to compute a new mapping given the key and its current mapped value.
containsKey​(Object key)Returns true if this map contains a mapping for the specified key.
containsValue​(Object value)Returns true if this map maps one or more keys to the specified value.
entrySet()Returns a Set view of the mappings contained in this map.
equals​(Object o)Compares the specified object with this map for equality.
firstEntry()Returns a key-value mapping associated with the least key in this map, or null if the map is empty.
firstKey()Returns the first (lowest) key currently in this map.
floorEntry​(K key)Returns a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key.
floorKey​(K key)Returns the greatest key less than or equal to the given key, or null if there is no such key.
get​(Object key)Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
getOrDefault​(Object key, V defaultValue)Returns the value to which the specified key is mapped, or the given defaultValue if this map contains no mapping for the key.
headMap​(K toKey)Returns a view of the portion of this map whose keys are strictly less than toKey.
headMap​(K toKey, boolean inclusive)Returns a view of the portion of this map whose keys are less than (or equal to, if inclusive is true) toKey.
higherEntry​(K key)Returns a key-value mapping associated with the least key strictly greater than the given key, or null if there is no such key.
higherKey​(K key)Returns the least key strictly greater than the given key, or null if there is no such key.
keySet()Returns a NavigableSet view of the keys contained in this map.
lastEntry()Returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
lastKey()Returns the last (highest) key currently in this map.
lowerEntry​(K key)Returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key.
lowerKey​(K key)Returns the greatest key strictly less than the given key, or null if there is no such key.
merge​(K key, V value, BiFunction<? super V,​? super V,​? extends V> remappingFunction)If the specified key is not already associated with a value, associates it with the given value.
pollFirstEntry()Removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.
pollLastEntry()Removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
put​(K key, V value)Associates the specified value with the specified key in this map.
putIfAbsent​(K key, V value)If the specified key is not already associated with a value, associates it with the given value.
remove​(Object key)Removes the mapping for the specified key from this map if present.
remove​(Object key, Object value)Removes the entry for a key only if currently mapped to a given value.
replace​(K key, V value)Replaces the entry for a key only if currently mapped to some value.
replace​(K key, V oldValue, V newValue)Replaces the entry for a key only if currently mapped to a given value.
subMap​(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)Returns a view of the portion of this map whose keys range from fromKey to toKey.
subMap​(K fromKey, K toKey)Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.
tailMap​(K fromKey)Returns a view of the portion of this map whose keys are greater than or equal to fromKey.
tailMap​(K fromKey, boolean inclusive)Returns a view of the portion of this map whose keys are greater than (or equal to, if inclusive is true) fromKey.
values()Returns a Collection view of the values contained in this map.

Methods declared in class java.util.AbstractMap

METHOD

DESCRIPTION

hashCode()Returns the hash code value for this map.
isEmpty()Returns true if this map contains no key-value mappings.
putAll​(Map<? extends K,​? extends V> m)Copies all of the mappings from the specified map to this map (optional operation).
size()Returns the number of key-value mappings in this map.
toString()Returns a string representation of this map.

Methods declared in interface java.util.concurrent.ConcurrentMap

METHOD

DESCRIPTION

forEach​(BiConsumer<? super K,​? super V> action)Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
replaceAll​(BiFunction<? super K,​? super V,​? extends V> function)Replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.

Methods declared in interface java.util.concurrent.ConcurrentNavigableMap

METHOD



DESCRIPTION

descendingKeySet()Returns a reverse order NavigableSet view of the keys contained in this map.
descendingMap()Returns a reverse order view of the mappings contained in this map.
navigableKeySet()Returns a NavigableSet view of the keys contained in this map.

Methods declared in interface java.util.Map

METHOD

DESCRIPTION

hashCode()Returns the hash code value for this map.
isEmpty()Returns true if this map contains no key-value mappings.
putAll​(Map<? extends K,​? extends V> m)Copies all of the mappings from the specified map to this map (optional operation).
size()Returns the number of key-value mappings in this map.

Methods declared in interface java.util.SortedMap

METHOD

DESCRIPTION

comparator()Returns the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.

Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ConcurrentSkipListMap.html

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :