Program to convert set of Integer to Array of Integer in Java

Java 8Object Oriented ProgrammingProgramming

Let’s say the following is our set of Integer −

Set<Integer> set = new HashSet<>(Arrays.asList(50, 100, 150, 200, 400, 600, 800, 1000, 1200, 1500));

Now, convert it to Array of Integer −

int[] arr = set.stream()
   .mapToInt(Integer::intValue)
   .toArray();

Example

Following is the program to convert set of Integer to Array of Integer in Java −

import java.util.*;
import java.util.stream.*;
import java.util.function.Function;
public class Demo {
   public static void main(String args[]) {
      Set<Integer> set = new HashSet<>(Arrays.asList(50, 100, 150, 200, 400, 600, 800, 1000, 1200, 1500));
      System.out.println("Set = " + set);
      int[] arr = set.stream().mapToInt(Integer::intValue).toArray();
      System.out.println("Array = "+ Arrays.toString(arr));
   }
}

Output

Set = [400, 800, 1200, 50, 100, 150, 200, 600, 1000, 1500]
Array = [400, 800, 1200, 50, 100, 150, 200, 600, 1000, 1500]
raja
Published on 23-Sep-2019 17:26:08
Advertisements