在 Java 中创建并发集

在 JDK 8 之前,Java 不支持并发哈希集。现在,ConcurrentHashMap 用于在 Java 中创建并发集。

ConcurrentHashMap 具有函数 KeySet()newKeySet() 在 Java 中创建并发散列集。

本教程演示了如何在 Java 中创建并发哈希集。

在 Java 中使用 ConcurrentHashMapKeySet() 函数创建并发集

使用 ConcurrentHashMapKeySet() 我们可以在 Java 中创建一个并发集。

package delftstack;
import java.io.*;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
class ConcurrentSet {
    public static void main (String[] args) {
        // Creating a concurrent hash map
        ConcurrentHashMap<String,Integer> demo_map = new ConcurrentHashMap<>();
        demo_map.put("Delftstack",10);
        demo_map.put("Jack",20);
        demo_map.put("John", 30);
        demo_map.put("Mike",40);
        demo_map.put("Michelle", 50);
        // use keySet() to create a set from the concurrent hashmap
        Set keyset_conc_set = demo_map.keySet();
        System.out.println("The concurrent set using keySet() function is : " + keyset_conc_set);
    }
}

该代码从并发 HashMap 创建一组并发名称。我们不能使用 add() 方法向集合中添加更多成员;它会抛出一个错误。

输出:

The concurrent set using keySet() function is : [Michelle, Mike, Delftstack, John, Jack]

在 Java 中使用 ConcurrentHashMapnewKeySet() 函数创建并发集

newKeySet() 用于创建一个可以稍后操作的并发集合,从集合中添加或删除元素。

package delftstack;
import java.io.*;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
class ConcurrentSet {
    public static void main (String[] args) {
        // Create a concurrent set using concorrentHashMap and newkeyset()
        Set <String> newKeySet_conc_set = ConcurrentHashMap.newKeySet();
        newKeySet_conc_set.add("Mike");
        newKeySet_conc_set.add("Michelle");
        newKeySet_conc_set.add("John");
        newKeySet_conc_set.add("Jack");
        // Print the concurrent set
        System.out.println("The concurrent set before adding the element: " + newKeySet_conc_set);
        // Add new element
        newKeySet_conc_set.add("Delftstack");
        // Show the change
        System.out.println("The concurrent set after adding the element: " + newKeySet_conc_set);
        // Check any element using contains
        if(newKeySet_conc_set.contains("Delftstack")){
            System.out.println("Delftstack is a member of the set");
        }
        else{
            System.out.println("Delftstack is not a member of the set");
        }
        // Remove any element from the concurrent set
        newKeySet_conc_set.remove("Delftstack");
        System.out.println("The concurrent set after removing the element:  " + newKeySet_conc_set);
    }
}

上面的代码从 ConcurrentHashMapnewKeySet 函数生成一个并发集,然后添加、删除和检查元素。

输出:

The concurrent set before adding the element: [Michelle, Mike, John, Jack]
The concurrent set after adding the element: [Michelle, Mike, Delftstack, John, Jack]
Delftstack is a member of the set
The concurrent set after removing the element:  [Michelle, Mike, John, Jack]