Java Set – Java 中的 Set
Java Set 是元素(或对象)的集合,不包含重复元素。Java Set 是扩展 Collection 接口的接口。与 List 不同,Java Set 不是有序集合,其元素没有特定的顺序。Java Set 不提供对插入元素位置的控制。您无法通过索引访问元素,也无法在列表中搜索元素。
Java 集
在本节中,我们将讨论有关 Java Set 的一些要点:
- Java Set 接口是 Java 集合框架的一个成员。
- 与 List 不同,Set不允许您添加重复元素。
- Set 最多只允许您添加一个空元素。
- Set 接口在 Java 8 中有一个默认方法:splitterator。
- 与 List 和数组不同,Set 不支持其元素的索引或位置。
- Set 支持泛型,我们应该尽可能使用它。将泛型与 Set 结合使用可避免运行时出现 ClassCastException。
- 我们可以使用 Set 接口实现来维护唯一元素。
Java集合类图
Java Set 接口扩展了 Collection 接口。Collection 接口扩展了 Iterable 接口。一些常用的 Set 实现类是 HashSet、LinkedHashSet、TreeSet、CopyOnWriteArraySet 和 ConcurrentSkipListSet。AbstractSet 提供了 Set 接口的骨架实现,以减少实现 Set 的工作量。
Java Set 方法
在本节中,我们将讨论一些有用的 Java Set 方法:
- int size():获取Set中元素的数量。
- boolean isEmpty():检查 Set 是否为空。
- boolean contains(Object o):如果此 Set 包含指定元素,则返回 true。
- 迭代器 iterator():返回此集合中元素的迭代器。返回的元素没有特定的顺序。
- Object[] toArray():返回包含此集合中所有元素的数组。如果此集合对其迭代器返回元素的顺序做出任何保证,则此方法必须以相同顺序返回元素。
- boolean add(E e):如果指定元素尚不存在,则将其添加到此集合(可选操作)。
- boolean remove(Object o):如果存在,则从此集合中删除指定元素(可选操作)。
- boolean removeAll(Collection c):从此集合中删除指定集合中包含的所有元素(可选操作)。
- boolean retainAll(Collection c):仅保留此集合中包含在指定集合中的元素(可选操作)。
- void clear():从集合中删除所有元素。
- 迭代器 iterator():返回此集合中元素的迭代器。
Java 数组设置
Unlike List, We cannot convert a Java Set into an array directly as it’s NOT implemented using an Array. So We cannot use Arrays class to get the view of array as set. We can follow another approach. We can convert an array into List using Arrays.asList() method, then use it to create a Set. By using this approach, we can covert a Java Array to Set in two ways. Let us discuss them one by one using one simple example. Approach-1 In this approach, first We need to create a List using given array and use it to create a Set as shown below.
import java.util.*;
public class ArrayToSet {
public static void main(String[] args) {
String[] vowels = {"a","e","i","o","u"};
Set<String> vowelsSet = new HashSet>(Arrays.asList(vowels));
System.out.println(vowelsSet);
/**
* Unlike List, Set is NOt backed by array,
* so we can do structural modification without any issues.
*/
vowelsSet.remove("e");
System.out.println(vowelsSet);
vowelsSet.clear();
System.out.println(vowelsSet);
}
}
Approach-2 In this approach, we do NOT use intermediate List to create a Set from an Array. First create an empty HashSet, then use Collections.addAll() to copy array elements into the given Set as shown below.
import java.util.*;
public class ArrayToSet2 {
public static void main(String[] args) {
String[] vowels = {"a","e","i","o","u"};
Set<String> vowelsSet = new HashSet<>();
Collections.addAll(vowelsSet, vowels);
System.out.println(vowelsSet);
/**
* Unlike List, Set is NOt backed by array,
* so we can do structural modification without any issues.
*/
vowelsSet.remove("e");
System.out.println(vowelsSet);
vowelsSet.clear();
System.out.println(vowelsSet);
}
}
Output:- When we run above two programs, we will get the same output as shown below.
[a, e, u, i, o]
[a, u, i, o]
[]
Java Set to Array
In this section, we will write a program to convert a Set of Strings into an Array of String using Set.toArray() method as shown below.
import java.util.*;
public class SetToArray {
public static void main(String[] args) {
Set<String< vowelsSet = new HashSet<>();
// add example
vowelsSet.add("a");
vowelsSet.add("e");
vowelsSet.add("i");
vowelsSet.add("o");
vowelsSet.add("u");
//convert Set to Array
String strArray[] = vowelsSet.toArray(new String[vowelsSet.size()]);
System.out.println(Arrays.toString(strArray));
}
}
Output:- When we run above program, we will get the following output as shown below.
[a, e, u, i, o]
Java Set Sorting
As we know, Set (HashSet) does NOT support sorting elements directly. It stores and display it’s elements in random order. However, we have some approaches to sort it’s elements as shown below:
import java.util.*;
public class SetSortingExample {
public static void main(String[] args) {
Set<Integer> intsSet = new HashSet<>();
Random random = new Random();
for (int i = 0; i {return (o2-o1);});
System.out.println("Reverse Sorting: " + intsList2);
// Approach-3
Set<Integer> sortedSet = new TreeSet<>(intsSet);
System.out.println("Sorted Set: " + sortedSet);
}
}
Output:- When we run above program, we will see the following output.
[560, 864, 176, 657, 135, 103, 40, 123, 555, 589]
Natural Sorting: [40, 103, 123, 135, 176, 555, 560, 589, 657, 864]
Before Sorting: [560, 864, 176, 657, 135, 103, 40, 123, 555, 589]
Reverse Sorting: [864, 657, 589, 560, 555, 176, 135, 123, 103, 40]
Sorted Set: [40, 103, 123, 135, 176, 555, 560, 589, 657, 864]
Java Set Common Operations
Most common operations performed on Java Set are add, addAll, clear, size etc. Below is a simple Java Set example showing common method usage.
import java.util.*;
public class SetCommonOperations
{
public static void main(String args[])
{
Set<String> vowels= new HashSet<>();
//add example
vowels.add("A");
vowels.add("E");
vowels.add("I");
//We cannot insert elements based on index to a Set
System.out.println(vowels);
Set<String> set = new HashSet<>();
set.add("O");
set.add("U");
//appending set elements to letters
vowels.addAll(set);
System.out.println(vowels);
//clear example to empty the set
set.clear();
//size example
System.out.println("letters set size = " + vowels.size());
vowels.clear();
vowels.add("E"); vowels.add("E");vowels.add("I"); vowels.add("O");
System.out.println("Given set contains E element or not? = " + vowels.contains("E"));
}
}
Output:-
[A, E, I]
[A, E, U, I, O]
letters set size = 5
Given set contains E element or not? = true
Java Set Iterator
Below is a simple example showing how to iterate over Java Set.
import java.util.*;
public class SetIteratorExample
{
public static void main(String[] args)
{
Set<Integer> set = new HashSet<>();
for(int i=0; i<5; i++)
set.add(i);
Iterator iterator = set.iterator();
//simple iteration
while(iterator.hasNext()){
int i = (int) iterator.next();
System.out.print(i + ", ");
}
System.out.println("\n" + set);
//modification of set using iterator
iterator = set.iterator();
while(iterator.hasNext()){
int x = (int) iterator.next();
if(x%2 ==0) iterator.remove();
}
System.out.println(set);
//changing set structure while iterating
iterator = set.iterator();
while(iterator.hasNext()){
//ConcurrentModificationException here
int x = (int) iterator.next();
if(x==1) set.add(10);
}
}
}
Java Set to Stream
Below is a simple example showing how to convert a Java Set to Stream and perform some operations as per our requirements.
import java.util.*;
public class SetToStream {
public static void main(String[] args) {
Set<String> vowelsSet = new HashSet<>();
// add example
vowelsSet.add("a");
vowelsSet.add("e");
vowelsSet.add("i");
vowelsSet.add("o");
vowelsSet.add("u");
//convert set to stream
vowelsSet.stream().forEach(System.out::println);
}
}
Output:-
a
e
u
i
o
Java SE 9 Set
In Java SE 9 release, Oracle Corp is going to add some useful utility methods to Set interface. It’s better to understand them with some simple and useful examples. Please go through my tutorial at “Java SE 9: Set Factory Methods” to learn them. That’s all of a quick roundup on Set in Java. I hope these Java Set examples will help you in getting started with Set collection programming. Thank you for reading my tutorials. Please drop me a comment if you like my tutorials or have any issues or suggestions or any type errors.