在此程序中,您將學(xué)習(xí)如何在Java程序中如何實(shí)現(xiàn)數(shù)組(Array)與Set(HashSet)相互轉(zhuǎn)換。
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);
}
}運(yùn)行該程序時(shí),輸出為:
Set: [a, b, c]
在上面的程序中,我們有一個(gè)名為array的數(shù)組。要將數(shù)組轉(zhuǎn)換為set,首先使用asList()將其轉(zhuǎn)換為list,因?yàn)镠ashSet接受list作為構(gòu)造函數(shù)
然后,我們使用轉(zhuǎn)換后的列表的元素初始化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);
}
}該程序的輸出與示例1相同。
在上面的程序中,不是先將數(shù)組轉(zhuǎn)換為列表再轉(zhuǎn)換為集合,而是使用流將數(shù)組轉(zhuǎn)換為集合
我們首先使用stream()方法將數(shù)組轉(zhuǎn)換為流,并使用以toSet()作為參數(shù)的collect()方法將流轉(zhuǎn)換為集合
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));
}
}運(yùn)行該程序時(shí),輸出為:
Array: [a, b, c]
在上面的程序中,我們有一個(gè)名為set的HashSet。要將set轉(zhuǎn)換為數(shù)組,我們首先創(chuàng)建一個(gè)與set長度相等的數(shù)組,并使用toArray()方法。