4

How to convert List of arrays into a single array in Java. Is there any predefined function to use?

Below is the list of arrays, I want to iterate and keep all values in a single array.

List<Integer[]> integerArrayList = new ArrayList<Integer[]>();

Integer[] resultArray = {};

Is there efficient way to implement?

0

2 Answers 2

7

Java 8's stream make this pretty easy:

Integer[] resultArray = 
    integerArrayList.stream().flatMap(Arrays::stream).toArray(Integer[]::new);
Sign up to request clarification or add additional context in comments.

Comments

4

With Streams:

Integer[] resultArray = integerArrayList.stream () // create a Stream<Integer[]>
                                        .flatMap (Stream::of) // flatten to a Stream<Integer>
                                        .toArray (Integer[]::new); // generate Integer[]

Similarly, you can produce an int[]:

int[] resultArray2 = integerArrayList.stream () // create a Stream<Integer[]>
                                     .flatMap (Stream::of) // flatten to a Stream<Integer>
                                     .mapToInt(Integer::intValue) // convert to IntStream
                                     .toArray (); // generate int[]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.