[Java Basics] Detailed explanation of Java Set: Easily manage unique elements

Insert image description here

In Java programming, collections are a very important concept that allow us to store and manage a set of objects efficiently. One of them is Seta set, which is an unordered, non-repeating data structure that is ideal for storing unique elements. This blog will take an in-depth look at collections in Java Set, from basic concepts to advanced usage, presenting you with comprehensive information.

1. What is a Set?

SetIt is part of the Java collection framework and represents a collection of unique elements. This means that Setno duplicate elements are allowed and each element is unique in the set. SetCollections are typically used to store unordered, non-repeating objects, such as a unique set of integers or strings.

2. Create and initialize the Set collection

In Java, different implementation classes can be used to create and initialize Setcollections. The following are some common initialization methods:

Set<String> set1 = new HashSet<>(); // 使用 HashSet 初始化
Set<Integer> set2 = new TreeSet<>(); // 使用 TreeSet 初始化
Set<Double> set3 = new LinkedHashSet<>(); // 使用 LinkedHashSet 初始化

These initialization methods use HashSet, TreeSetand LinkedHashSetas Setthe underlying implementation of the collection respectively. Each implementation class has its own characteristics, and we will introduce them in detail later.

3. Basic operations

3.1 Add elements

Adding elements to Seta collection is very simple, addjust use the method. This method will ensure that elements are not repeated.

Set<String> fruits = new HashSet<>();
fruits.add("苹果");
fruits.add("香蕉");
fruits.add("橙子");

3.2 Delete elements

To Setremove elements from a collection, you can use removethe method. This will delete the specified element.

fruits.remove("香蕉");

3.3 Query elements

To query whether an element is contained, you can use containsthe method.

boolean hasApple = fruits.contains("苹果");

4. Traverse the Set collection

Traversing Seta collection usually uses iterators or enhanced for-eachloops.

4.1 Using iterators

Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
    
    
    String fruit = iterator.next();
    System.out.println(fruit);
}

4.2 Using the enhanced for-each loop

for (String fruit : fruits) {
    
    
    System.out.println(fruit);
}

5. Set implementation class of collection

Java provides a variety of Setcollection implementation classes, each of which has its own unique characteristics. Here are some common implementation classes:

5.1 HashSet

HashSetIt is one of the most commonly used Setcollection implementation classes. It uses hash tables to store elements and provides fast insertion, deletion and query operations. However, it does not guarantee the order of the elements, i.e. the elements HashSetare unordered in .

5.2 TreeSet

TreeSetIt is a collection implemented based on the red-black tree data structure Set. It ensures that elements are arranged in ascending or descending order and supports efficient element retrieval, insertion, and deletion. Therefore, if you need to sort the elements, you can choose to use it TreeSet.

5.3 LinkedHashSet

LinkedHashSetIs HashSeta subclass of which internally uses a linked list to maintain the order of elements. Therefore, LinkedHashSetthe insertion order of elements is maintained and can be traversed in the order of insertion. You can choose to use this if you need to maintain the insertion order of elements LinkedHashSet.

6. Performance considerations for Set collections

When choosing to use Seta collection, consider performance. Here are some performance considerations:

  • HashSetTypically performs better than TreeSetand LinkedHashSetbecause it uses hash tables, providing fast insertion, deletion, and query operations.
  • TreeSetThe performance depends on the sort order of the elements, and insertion and deletion operations are generally slower.
  • LinkedHashSetThe performance is similar to HashSet, but it also maintains the insertion order of elements.

It is very important to choose an implementation class that suits your needs, and it should be decided based on the specific scenario.

7. Precautions for use

When using Setcollections, you need to pay attention to the following things:

  • SetDuplicate elements are not allowed, so adding duplicate elements will be ignored.
  • SetCollections generally do not guarantee the order of elements, if order is required, consider using LinkedHashSetor TreeSet.
  • SetCollections are not thread-safe. If used in a multi-threaded environment, you need to consider synchronization operations or use a thread-safe collection implementation.

8. Advanced usage

8.1 Set operations

SetSets support a range of set operations such as union, intersection, and difference. You can use methods such as addAll, retainAlland removeAllto perform these operations.

Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3));
Set<Integer> set2 = new HashSet<>(Arrays.asList(2, 3, 4));

// 求并集
Set<Integer> union = new HashSet<>(set1);
union.addAll(set2);

// 求交集
Set<Integer> intersection = new HashSet<>(set1);
intersection.retainAll(set2);

// 求差集
Set<Integer> difference = new HashSet<>(set1);
difference.removeAll(set2);

8.2 Set conversion

SetCollections can be easily converted to other collection types. For example, Setconvert to an array or list, or an array or list to Set.

Set<String> set = new HashSet<>(Arrays.asList("apple", "banana", "cherry"));

// 将 Set 转换为数组
String[] array = set.toArray(new String[0]);

// 将 Set 转换为列表
List<String> list = new ArrayList<>(set);

// 将数组转换为 Set
Set<Integer> integerSet = new HashSet<>(Arrays.asList(1, 2, 3));

// 将列表转换为 Set
Set<Double> doubleSet = new HashSet<>(Arrays.asList(1.0, 2.0, 3.0));

8.3 More uses of Set collections

8.3.1 Determine whether the set is empty

You can use isEmpty()the method to check Setif a is empty. This is useful when you need to verify whether a collection contains an element.

Set<String> set = new HashSet<>();
boolean isEmpty = set.isEmpty(); // 返回 true,因为集合是空的

8.3.2 Get the size of a collection

Use size()the method to get Setthe number of elements in the collection.

Set<String> set = new HashSet<>();
int size = set.size(); // 返回 0,因为集合是空的

8.3.3 Converting a collection to an immutable collection

Sometimes, you may want to convert a mutable Setcollection to an immutable collection to avoid accidentally modifying the collection. You can use Collections.unmodifiableSet()the method to achieve this.

Set<String> mutableSet = new HashSet<>();
// 添加元素到可变集合
Set<String> unmodifiableSet = Collections.unmodifiableSet(mutableSet);

// 尝试修改不可修改的集合将抛出异常
unmodifiableSet.add("新元素"); // 抛出 UnsupportedOperationException

8.3.4 Using addAllmerge collections

If you need to Setmerge two collections into one, you can use addAllthe method.

Set<String> set1 = new HashSet<>(Arrays.asList("apple", "banana"));
Set<String> set2 = new HashSet<>(Arrays.asList("banana", "cherry"));

set1.addAll(set2); // 将 set2 中的元素合并到 set1 中

System.out.println(set1); // 输出 [banana, apple, cherry]

8.3.5 Use to removeAlldelete elements from a collection

If you need to Setremove elements from one collection in another collection, you can use removeAllthe method.

Set<String> set1 = new HashSet<>(Arrays.asList("apple", "banana", "cherry"));
Set<String> set2 = new HashSet<>(Arrays.asList("banana", "cherry"));

set1.removeAll(set2); // 从 set1 中删除 set2 中的元素

System.out.println(set1); // 输出 [apple]

8.3.6 Use to retainAllretain common elements in a collection

If you only want to keep Setelements common to both collections, you can use retainAllthe method.

Set<String> set1 = new HashSet<>(Arrays.asList("apple", "banana", "cherry"));
Set<String> set2 = new HashSet<>(Arrays.asList("banana", "cherry", "date"));

set1.retainAll(set2); // 保留 set1 和 set2 中的共同元素

System.out.println(set1); // 输出 [banana, cherry]

8.3.7 Use stream()to perform operations

The Stream API introduced in Java 8 allows you to perform various operations on collections more conveniently, including filtering, mapping, aggregation, etc.

Set<String> fruits = new HashSet<>(Arrays.asList("apple", "banana", "cherry", "date"));

// 使用 Stream 过滤元素
Set<String> filteredFruits = fruits.stream()
        .filter(fruit -> fruit.startsWith("a"))
        .collect(Collectors.toSet());

System.out.println(filteredFruits); // 输出 [apple]

8.3.8 forEachTraversing elements using

The method introduced in Java 8 forEachcan conveniently traverse the elements in a collection.

Set<String> fruits = new HashSet<>(Arrays.asList("apple", "banana", "cherry"));

fruits.forEach(fruit -> {
    
    
    System.out.println(fruit); // 分别输出每个水果
});

These advanced usages can help you use collections more flexibly Setand choose the appropriate methods and techniques to process data based on your specific needs. Whether it is processing the addition, deletion, modification, and query of elements, or performing set operations and conversions, Java's Setcollections provide a wealth of functions to meet various programming needs.

9. Sample code

Here is some Setsample code using collections:

// 创建一个 HashSet
Set<String> fruits = new HashSet<>();

// 添加元素
fruits.add("苹果");
fruits.add("香蕉");
fruits.add("橙子");

// 删除元素
fruits.remove("香蕉");

// 查询元素
boolean hasApple = fruits.contains("苹果");

// 遍历集合
for (String fruit : fruits) {
    
    
    System.out.println(fruit);
}

10. Summary

SetSet is a very useful data structure in Java for storing unique elements. This blog introduces Setthe basic concepts of collections, creation and initialization, basic operations, traversal, different implementation classes, performance considerations, usage notes, advanced usage, and sample code. I hope that through the introduction of this article, you Setwill have a deeper understanding of collections and be able to use them flexibly in actual programming. Both beginners and experienced developers can Setimprove the efficiency and maintainability of their code by mastering collections.

Guess you like

Origin blog.csdn.net/qq_21484461/article/details/132795997