Close

Java 8 Streams - Stream.toArray Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.Stream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.StreamStreamLogicBig

Methods:

Object[] toArray()

This terminal operation returns an array containing the elements of this stream.



<A> A[] toArray(IntFunction<A[]> generator)

This terminal operation returns an array containing the elements of this stream, using the provided generator function to allocate the returned array.


Examples


package com.logicbig.example.stream;

import java.util.Arrays;
import java.util.stream.Stream;

public class ToArrayExample {

public static void main(String... args) {
Stream<String> stream = Stream.of("one", "two", "three", "four");
Object[] objects = stream.toArray();
System.out.println(Arrays.toString(objects));
}
}

Output

[one, two, three, four]




package com.logicbig.example.stream;

import java.util.Arrays;
import java.util.stream.Stream;

public class ToArrayExample2 {

public static void main(String... args) {
String[] strings = Stream.of("one", "two", "three", "four")
.filter(s -> s.startsWith("t"))
.toArray(String[]::new);
System.out.println(Arrays.toString(strings));
}
}

Output

[two, three]




See Also