Java程序将数组转换为Set
java.util包的Arrays类提供了一种称为的方法asList()。此方法接受数组作为参数,然后返回List对象。要将数组转换为Set对象-
创建一个数组或从用户那里读取它。
使用asList()Arrays类的方法将数组转换为列表对象。
将此列表传递给HashSet对象的构造函数。
打印Set对象的内容。
示例
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class ArrayToSet {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array to be created ::");
int size = sc.nextInt();
String [] myArray = new String[size];
for(int i=0; i<myArray.length; i++){
System.out.println("Enter the element "+(i+1)+" (String) :: ");
myArray[i]=sc.next();
}
Set<String> set = new HashSet<>(Arrays.asList(myArray));
System.out.println("Given array is converted to a Set");
System.out.println("Contents of set ::"+set);
}
}输出结果
Enter the size of the array to be created :: 4 Enter the element 1 (String) :: Ram Enter the element 2 (String) :: Rahim Enter the element 3 (String) :: Robert Enter the element 4 (String) :: Rajeev Given array is converted to a Set Contents of set ::[Robert, Rahim, Rajeev, Ram]