English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to implement the conversion between array (Array) and set (HashSet) in a Java program.
import java.util.*; public class ArraySet { public static void main(String[] args) { String[] array = {"a", "b", "c"}; Set<String> set = new HashSet<>(Arrays.asList(array)); System.out.println("Set: " ); + set); } }
When running the program, the output is:
Set: [a, b, c]
In the above program, we have an array named array. To convert the array to a set, first use asList() to convert it to a list, because HashSet accepts list as a constructor
Then, we use the elements of the converted list to initialize the set
import java.util.*; public class ArraySet { public static void main(String[] args) { String[] array = {"a", "b", "c"}; Set<String> set = new HashSet<>(Arrays.stream(array).collect(Collectors.toSet())); System.out.println("Set: " ); + set); } }
The output of the program is similar to the example1The same.
In the above program, it is not the case that the array is first converted to a list and then to a set, but the array is converted to a set using a stream
We first use the stream() method to convert the array to a stream, and then use the collect() method with toSet() as a parameter to convert the stream to a set
import java.util.*; public class SetArray { public static void main(String[] args) { Set<String> set = new HashSet<>(); set.add("a"); set.add("b"); set.add("c"); String[] array = new String[set.size()]; set.toArray(array); System.out.println("Array: ", + Arrays.toString(array)); } }
When running the program, the output is:
Array: [a, b, c]
In the above program, we have a HashSet named set. To convert set to an array, we first create an array of the same length as set and use the toArray() method.