[java] How to convert a Java 8 Stream to an Array?

What is the easiest/shortest way to convert a Java 8 Stream into an array?

This question is related to java arrays java-8 java-stream

The answer is


you can use the collector like this

  Stream<String> io = Stream.of("foo" , "lan" , "mql");
  io.collect(Collectors.toCollection(ArrayList<String>::new));

You can do it in a few ways.All the ways are technically the same but using Lambda would simplify some of the code. Lets say we initialize a List first with String, call it persons.

List<String> persons = new ArrayList<String>(){{add("a"); add("b"); add("c");}};
Stream<String> stream = persons.stream();

Now you can use either of the following ways.

  1. Using the Lambda Expresiion to create a new StringArray with defined size.

    String[] stringArray = stream.toArray(size->new String[size]);

  2. Using the method reference directly.

    String[] stringArray = stream.toArray(String[]::new);


If you want to get an array of ints, with values from 1 to 10, from a Stream<Integer>, there is IntStream at your disposal.

Here we create a Stream with a Stream.of method and convert a Stream<Integer> to an IntStream using a mapToInt. Then we can call IntStream's toArray method.

Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9,10);
//or use this to create our stream 
//Stream<Integer> stream = IntStream.rangeClosed(1, 10).boxed();
int[] array =  stream.mapToInt(x -> x).toArray();

Here is the same thing, without the Stream<Integer>, using only the IntStream:

int[]array2 =  IntStream.rangeClosed(1, 10).toArray();

You can create a custom collector that convert a stream to array.

public static <T> Collector<T, ?, T[]> toArray( IntFunction<T[]> converter )
{
    return Collectors.collectingAndThen( 
                  Collectors.toList(), 
                  list ->list.toArray( converter.apply( list.size() ) ) );
}

and a quick use

List<String> input = Arrays.asList( ..... );

String[] result = input.stream().
         .collect( CustomCollectors.**toArray**( String[]::new ) );

import java.util.List;
import java.util.stream.Stream;

class Main {

    public static void main(String[] args) {
        // Create a stream of strings from list of strings
        Stream<String> myStreamOfStrings = List.of("lala", "foo", "bar").stream();

        // Convert stream to array by using toArray method
        String[] myArrayOfStrings = myStreamOfStrings.toArray(String[]::new);

        // Print results
        for (String string : myArrayOfStrings) {
            System.out.println(string);
        }
    }
}

Try it out online: https://repl.it/@SmaMa/Stream-to-array


     Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);

     Integer[] integers = stream.toArray(it->new Integer[it]);

You can convert a java 8 stream to an array using this simple code block:

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

But let's explain things more, first, let's Create a list of string filled with three values:

String[] stringList = {"Bachiri","Taoufiq","Abderrahman"};

Create a stream from the given Array :

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

we can now perform some operations on this stream Ex:

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

and finally convert it to a java 8 Array using these methods:

1-Classic method (Functional interface)

IntFunction<String[]> intFunction = new IntFunction<String[]>() {
    @Override
    public String[] apply(int value) {
        return new String[value];
    }
};


String[] myNewArray = myNewStream.toArray(intFunction);

2 -Lambda expression

 String[] myNewArray2 = myNewStream.toArray(value -> new String[value]);

3- Method reference

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

Method reference Explanation:

It's another way of writing a lambda expression that it's strictly equivalent to the other.


Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);

int[] arr=   stream.mapToInt(x->x.intValue()).toArray();

Convert text to string array where separating each value by comma, and trim every field, for example:

String[] stringArray = Arrays.stream(line.split(",")).map(String::trim).toArray(String[]::new);

Using the toArray(IntFunction<A[]> generator) method is indeed a very elegant and safe way to convert (or more correctly, collect) a Stream into an array of the same type of the Stream.

However, if the returned array's type is not important, simply using the toArray() method is both easier and shorter. For example:

    Stream<Object> args = Stream.of(BigDecimal.ONE, "Two", 3);
    System.out.printf("%s, %s, %s!", args.toArray());

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to java-8

Default interface methods are only supported starting with Android N Class has been compiled by a more recent version of the Java Environment Why is ZoneOffset.UTC != ZoneId.of("UTC")? Modify property value of the objects in list using Java 8 streams How to use if-else logic in Java 8 stream forEach Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit What are functional interfaces used for in Java 8? java.time.format.DateTimeParseException: Text could not be parsed at index 21 Java 8 lambda get and remove element from list

Examples related to java-stream

Sorting a list with stream.sorted() in Java Modify property value of the objects in list using Java 8 streams How to use if-else logic in Java 8 stream forEach Java 8 lambda get and remove element from list Create list of object from another using Java 8 Streams Java 8 Stream API to find Unique Object matching a property value Reverse a comparator in Java 8 Ignore duplicates when producing map using streams Modifying Objects within stream in Java8 while iterating How can I get a List from some class properties with Java 8 Stream?