如何使用Java将整数集合转换为int数组?


Java 中的集合对象是指存储其他对象引用的对象。 java.util 包提供了集合的类和接口。主要有四个集合接口,分别是 Set 列表、队列、映射。

Set − Set 对象是一个存储元素组的集合,它可以动态增长,并且不允许重复元素。

HashSet 和 LinkedHashSet 是实现 Set 接口的类。您可以通过实现这两个类中的任何一个来创建一个 Set 对象。

示例

import java.util.HashSet;
public class SetExample {
   public static void main(String args[]) {
      //Instantiating the HashSet
      HashSet<String> hashSet = new HashSet<String>();
      //Populating the HashSet
      hashSet.add("Mango");
      hashSet.add("Apple");
      hashSet.add("Cherries");
      hashSet.add("Banana");
      System.out.println(hashSet);
   }
}

输出

[Apple, Mango, Cherries, Banana]

将 Set 对象转换为数组

您可以通过多种方式将 Set 对象转换为数组 -

添加每个元素 − 您可以使用 foreach 循环将 Set 对象的每个元素添加到数组中。

示例

import java.util.HashSet;
import java.util.Set;
public class SetExample {
   public static void main(String args[]) {
      //Instantiating the HashSet
      Set<Integer> hashSet = new HashSet<Integer>();
      //Populating the HashSet
      hashSet.add(1124);
      hashSet.add(3654);
      hashSet.add(7854);
      hashSet.add(9945);
      System.out.println(hashSet);
      //Creating an empty integer array
      Integer[] array = new Integer[hashSet.size()];
      //Converting Set object to integer array
      int j = 0;
      for (Integer i: hashSet) {
         array[j++] = i;
      }
   }
}

输出

[1124, 3654, 9945, 7854]

使用 toArray() 方法 − Set 接口的 toArray() 方法接受一个数组,用当前 Set 对象中的所有元素填充它,并返回它。使用此方法,您可以将 Set 对象转换为数组。

示例

import java.util.HashSet;
import java.util.Set;
public class SetExample {
   public static void main(String args[]) {
      //Instantiating the HashSet
      Set<Integer> hashSet = new HashSet<Integer>();
      //Populating the HashSet
      hashSet.add(1124);
      hashSet.add(3654);
      hashSet.add(7854);
      hashSet.add(9945);
      //Creating an empty integer array
      Integer[] array = new Integer[hashSet.size()];
      //Converting Set object to integer array
      hashSet.toArray(array);
      System.out.println(Arrays.toString(array));
   }
}

输出

[1124, 3654, 9945, 7854]

使用 Java8:自从 Java8 引入流以来,这些流提供了一种将集合对象转换为数组的方法。

示例

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class SetExample {
   public static void main(String args[]) {
      //Instantiating the HashSet
      Set<Integer> hashSet = new HashSet<Integer>();
      //Populating the HashSet
      hashSet.add(1124);
      hashSet.add(3654);
      hashSet.add(7854);
      hashSet.add(9945);
      System.out.println(hashSet);
      //Creating an empty integer array
      Integer[] array = hashSet.stream().toArray(Integer[]::new);
      System.out.println(Arrays.toString(array));
   }
}

输出

[1124, 3654, 9945, 7854]

更新于: 2020年7月2日

9K+ 浏览量

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.