将数组转换为集合的 Java 程序

java programming java8object oriented programming

java.util 包中的 Arrays 类提供了一个名为 asList() 的方法。此方法接受一个数组作为参数,并返回一个 List 对象。将数组转换为集合对象 −

  •  创建一个数组或从用户那里读取它。
  •  使用 Arrays 类的 asList() 方法将数组转换为列表对象。
  •  将此列表传递给 HashSet 对象的构造函数。
  •  打印集合对象的内容。

示例

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]

相关文章