• How to convert Integer Set to primitive int array.
  • By Using java 8 Streams we can convert Set to array.
  • set.stream().mapToInt(Number::intValue).toArray();
  • Lets see an example java program on how to convert integer set to int array using java 8

#1: Java Example program on converting Integer Set to int Array

  1. package com.instanceofjava;

  2. import java.util.Arrays;
  3. import java.util.HashSet;
  4. import java.util.Set;

  5. public class SetToArray {
  6. /**
  7.  * @author www.Instanceofjava.com
  8.  * @category interview programming questions
  9.  * 
  10.  * Description: convert Integer set to int array using java 8
  11.  *
  12.  */
  13. public static void main(String[] args) {
  14. Set<Integer> hashset= new HashSet<>(Arrays.asList(12,34,56,78,99));
  15. int[] array = hashset.stream().mapToInt(Number::intValue).toArray();
  16. for (int i : array) {
  17. System.out.println(i);
  18. }

  19. }

  20. }

Output:

  1. 34
  2. 99
  3. 56
  4. 12
  5. 78





integer set to integer array java


In Java, a Set is a collection that contains no duplicate elements and is unordered. To convert a Set to an array, you can use the toArray() method of the Set interface. This method returns an array containing all of the elements in the Set in the order they are returned by the iterator.

Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(3);

Integer[] array = set.toArray(new Integer[set.size()]);



In this example, we first create a HashSet of integers, add some elements to it, then we use the toArray method to convert it to an array of integers.

toArray(T[] a) method where we can pass an empty array of a specific type, the method will fill the array with the elements from the set, this is useful if you know the size of the array that you need.

converting a Set to an array in Java can be done using the toArray() method of the Set interface. The method returns an array containing all of the elements in the Set in the order they are returned by the iterator. This method can also accept an empty array of a specific type, the method will fill the array with the elements from the set.

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu