📌  相关文章
📜  Java中的 ConcurrentSkipListMap 示例

📅  最后修改于: 2022-05-13 01:55:01.201000             🧑  作者: Mango

Java中的 ConcurrentSkipListMap 示例

ConcurrentSkipListMap 类是Java集合框架的成员。它是在 JDK 1.6 中引入的,属于Java.util.concurrent包。 ConcurrentSkipListMap 是 ConcurrentNavigableMap 的可扩展实现。所有元素都根据自然顺序或在构建期间传递的 Comparator 进行排序。此类使用 SkipList 数据结构的并发变体,为插入、删除、更新和访问操作提供log(n)时间成本。这些操作对于多线程并发执行是安全的。

宣言

这里, K是键对象类型, V是值对象类型。

ConcurrentSkipListMap 的层次结构

ConcurrentSkipListMap-in-Java-with-Examples

它实现了 Serializable , Cloneable , ConcurrentMap, ConcurrentNavigableMap, Map, NavigableMap, SortedMap 接口并扩展了AbstractMap< K,V>类。

ConcurrentSkipListMap 的构造函数

1. ConcurrentSkipListMap() :构造一个新的空映射,根据键的自然顺序排序。

2. ConcurrentSkipListMap (Comparatorcomparator) :构造一个新的,空的map,按照指定的comparator排序。

3. ConcurrentSkipListMap (Map m) :构造一个包含与给定映射相同映射的新映射,根据键的自然顺序排序。

4. ConcurrentSkipListMap (SortedMap m) :构造一个包含与指定排序映射相同的映射并使用相同排序的新映射。

例子

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 cslm
            = new ConcurrentSkipListMap();
  
        // 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());
    }
}


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 cslm
            = new ConcurrentSkipListMap();
  
        // 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);
    }
}


Java
// Java Program Demonstrate removing
// mappings from ConcurrentSkipListMap
  
import java.util.concurrent.*;
  
class RemovingMappingsExample {
    public static void main(String[] args)
    {
  
        // Initializing the map
        ConcurrentSkipListMap cslm
            = new ConcurrentSkipListMap();
  
        // 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);
    }
}


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 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 > 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 entry
                = itr.next();
            System.out.println("Key = " + entry.getKey()
                               + ", Value = "
                               + entry.getValue());
        }
    }
}


输出
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

基本操作

1. 添加映射

ConcurrentSkipListMap 的 put() 方法将指定值与此映射中的指定键相关联。如果映射先前包含键的映射,则旧值将被替换。

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 cslm
            = new ConcurrentSkipListMap();
  
        // 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);
    }
}
输出
After put(): {1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9}

2. 删除映射

ConcurrentSkipListMap 的 remove() 方法从此映射中删除指定键的映射。如果该特定键没有映射,则该方法返回 null。执行此方法后,地图的大小会减小。要删除地图的第一个条目和最后一个条目,我们可以分别使用pollFirstEntry()pollLastEntry()

Java

// Java Program Demonstrate removing
// mappings from ConcurrentSkipListMap
  
import java.util.concurrent.*;
  
class RemovingMappingsExample {
    public static void main(String[] args)
    {
  
        // Initializing the map
        ConcurrentSkipListMap cslm
            = new ConcurrentSkipListMap();
  
        // 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);
    }
}
输出
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. 迭代

我们可以使用 Iterator 接口遍历集合框架的任何结构。由于迭代器处理一种类型的数据,我们使用 Entry< ? , ? > 将两种不同的类型解析为兼容的格式。然后使用 next() 方法打印 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 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 > 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 entry
                = itr.next();
            System.out.println("Key = " + entry.getKey()
                               + ", Value = "
                               + entry.getValue());
        }
    }
}
输出
Key = 0, Value = 0
Key = 1, Value = 1
Key = 2, Value = 2
Key = 3, Value = 3
Key = 4, Value = 4
Key = 5, Value = 5

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

在类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 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.

在接口Java.util.concurrent.ConcurrentMap 中声明的方法

METHOD

DESCRIPTION

forEach​(BiConsumer 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 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.

在接口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.

在接口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 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.

在接口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.

参考: Java : Java