This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

The problem

In Java 8, what is the easiest way to turn a stream into an array?

answer

Answer 1

The simplest way to do this is to use the toArray(IntFunction

Generator) method, which is also recommended by the Java API
[]>

String[] stringArray = stringStream.toArray(String[]::new);
Copy the code

This method does this by giving an integer (i.e. length) as an argument and then returning an array of strings (String[]). You can also write your own IntFunction:

The Stream < String > stringStream =... ; String[] stringArray = stringStream.toArray(size ->newString [size]);Copy the code

IntFunction

the purpose of the IntFunction

generator is to put the array length into A new array.
[]>
[]>

Example:

Stream<String< stringStream = Stream.of("a"."b"."c");
String[] stringArray = stringStream.toArray(size -> new String[size]);
Arrays.stream(stringArray).forEach(Ssytem.out::println);
Copy the code

Printed results:

a
b
c
Copy the code

Answer 2

If you want an array of type int from a Stream

, you can use IntSteam.

Create a Stream with a stream. of method, convert Stream

to IntStream with mapToInt, and then call IntStream’s toArray method.

// Use either of the following methods
Stream<Integer> stream = Stream.of(1.2.3.4.5.6.7.8.9.10);
// Stream<Integer> stream = IntStream.rangeClosed(1, 10).boxed();
int[] array =  stream.mapToInt(x -> x).toArray();
Copy the code

Then again, just use IntStream;

int[]array2 =  IntStream.rangeClosed(1.10).toArray();
Copy the code

Answer 3

A stream can be easily converted to an array with the following code:

String[] myNewArray3 = myNewStream.toArray(String[]::new);
Copy the code

First we create an array of three strings;

String[] stringList = {"Bachiri"."Taoufiq"."Abderrahman"};
Copy the code

Next we create a stream for the given array:

Stream<String> stringStream = Arrays.stream(stringList);
Copy the code

We can then perform a series of operations on this stream:

Stream<String> myNewStream = stringStream.map(s -> s.toUpperCase());
Copy the code

Finally, we can convert it to an array using the following method:

  1. Traditional approach (Functional interface)
IntFunction<String[]> intFunction = new IntFunction<String[]>() {
    @Override
    public String[] apply(int value) {
        return newString[value]; }}; String[] myNewArray = myNewStream.toArray(intFunction);Copy the code
  1. Lambda expressions
String[] myNewArray2 = myNewStream.toArray(value -> new String[value]);
Copy the code
  1. API methods
String[] myNewArray3 = myNewStream.toArray(String[]::new);
Copy the code

This method is actually another way of writing Lambda expressions, and is equivalent to the second method.

provenance

Stack Overflow: How to convert a Java 8 Stream to an Array?