- How to convert a Java 8 Stream to an Array?
- 9 Answers 9
- Java Stream toArray()
- Example 1: Converting Stream of String to Array of String
- Example 2: Converting an Infinite Stream to an Array
- Example 3: Stream filter and collect to an Array
- Convert Java Stream to Array
- 1. Using Stream.toArray(IntFunction)
- 2. Using Stream.toArray()
- 3. Using IntStream.toArray()
- 4. Using Collectors.toList()
- Java Stream collect to array
- Convert Steam to Array
- Collect Stream to Integer array
- Was this post helpful?
- You may also like:
- [Fixed] Unable to obtain LocalDateTime from TemporalAccessor
- Convert LocalDate to Instant in Java
- Convert Instant to LocalDate in Java
- Convert String to LocalDateTime in Java
- Format LocalDateTime to String in Java
- Java 8 – Find duplicate elements in Stream
- How to format Instant to String in java
- Java Date to LocalDate
- Java LocalDate to Date
- Java Stream to List
- Share this
- Related Posts
- Author
- Related Posts
- [Fixed] Unable to obtain LocalDateTime from TemporalAccessor
- Convert LocalDate to Instant in Java
- Convert Instant to LocalDate in Java
- Convert String to LocalDateTime in Java
- Format LocalDateTime to String in Java
- Java 8 – Find duplicate elements in Stream
How to convert a Java 8 Stream to an Array?
I’d suggest you to revert the rollback as the question was more complete and showed you had tried something.
@skiwi Thanks! but i thought the attempted code does not really add more information to the question, and nobody has screamed «show us your attempt» yet =)
@skiwi: Although I usually shout at the do-my-homework-instead-of-me questions, this particular question seems to be clearer to me without any additional mess. Let’s keep it tidy.
You can find a lot of answers and guidance in the official docs of the package: docs.oracle.com/javase/8/docs/api/java/util/stream/…
9 Answers 9
The easiest method is to use the toArray(IntFunction generator) method with an array constructor reference. This is suggested in the API documentation for the method.
String[] stringArray = stringStream.toArray(String[]::new);
What it does is find a method that takes in an integer (the size) as argument, and returns a String[] , which is exactly what (one of the overloads of) new String[] does.
You could also write your own IntFunction :
Stream stringStream = . ; String[] stringArray = stringStream.toArray(size -> new String[size]);
The purpose of the IntFunction generator is to convert an integer, the size of the array, to a new array.
Stream stringStream = Stream.of("a", "b", "c"); String[] stringArray = stringStream.toArray(size -> new String[size]); Arrays.stream(stringArray).forEach(System.out::println);
Java Stream toArray()
Learn to convert a Stream to an array using Stream toArray() API. In this totorial, we will see multiple examples for collecting the Stream elements into an array.
The toArray() method returns an array containing the elements of the given stream. This is a terminal operation.
Object[] toArray() T[] toArray(IntFunctiongenerator)
toArray() method is an overloaded method. The second method uses a generator function to allocate the returned array.
The generator function takes an integer, which is the size of the desired array and produces an array of the desired size.
Example 1: Converting Stream of String to Array of String
In the given example, we are converting a stream to an array using using toArray() API.
Stream tokenStream = Arrays.asList("A", "B", "C", "D").stream(); //stream String[] tokenArray = tokenStream.toArray(String[]::new); //array System.out.println(Arrays.toString(tokenArray));
Example 2: Converting an Infinite Stream to an Array
To convert an infinite stream into array, we must limit the stream to a finite number of elements.
Infinite stream of Integers
IntStream infiniteNumberStream = IntStream.iterate(1, i -> i+1); int[] intArray = infiniteNumberStream.limit(10) .toArray(); System.out.println(Arrays.toString(intArray));
Infinite boxed stream of Integers
IntStream infiniteNumberStream = IntStream.iterate(1, i -> i+1); Integer[] integerArray = infiniteNumberStream.limit(10) .boxed() .toArray(Integer[]::new); System.out.println(Arrays.toString(integerArray));
Example 3: Stream filter and collect to an Array
Sometimes we need to find specific items in stream and then add only those elements to array. Here, we can use Stream.filter() method to pass a predicate which will return only those elements who match the pre-condition.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Main < public static void main(String[] args) < ListemployeeList = new ArrayList<>(Arrays.asList( new Employee(1, "A", 100), new Employee(2, "B", 200), new Employee(3, "C", 300), new Employee(4, "D", 400), new Employee(5, "E", 500), new Employee(6, "F", 600))); Employee[] employeesArray = employeeList.stream() .filter(e -> e.getSalary() < 400) .toArray(Employee[]::new); System.out.println(Arrays.toString(employeesArray)); >>
[Employee [id=1, name=A, salary=100.0], Employee [id=2, name=B, salary=200.0], Employee [id=3, name=C, salary=300.0]]
We can use Stream toArray() function is variety of ways to collect stream elements into an array in all usescases.
Convert Java Stream to Array
On this page we will learn how to convert Java Stream into Array . The best way to convert is using Stream.toArray(IntFunction) method. In our examples we will convert Java Stream into Array in following ways.
1. We will use Stream.toArray(IntFunction) which will return the array of the desired type.
2. Using Stream.toArray() method which will return Object[] and then we change it into required datatype.
3. For integer stream we can use IntStream.toArray() that will return int[] . In the same way we can use LongStream.toArray() to get long[] and DoubleStream.toArray() to get double[] .
4. We can convert stream into list and then list into array. To convert stream into list we need to use collect(Collectors.toList()) on the stream and to convert list into array we can use List.toArray method.
Contents
1. Using Stream.toArray(IntFunction)
The toArray(IntFunction) method returns an array containing the elements of this stream using the provided generator as IntFunction . This method is terminal operation.
A[] toArray(IntFunction generator)
Parameters: Pass a generator as IntFunction which produces a new array of the desired type and the provided length.
Returns: The method returns an array consisting the elements of stream.
Throws: The method throws ArrayStoreException if the runtime type of any element of this stream is not assignable to the runtime component type of the generated array.
Example-1:
In this example we will convert stream of string into array of string.
List list = Arrays.asList(«A», «B», «C», «D»); String[] strArray = list.stream().toArray(String[]::new); for(String s : strArray)
The output will be A B C D. In the above example we have instantiated IntFunction as generator in toArray method using method reference.
Now find the example with lambda expression.
String[] strArray = list.stream().toArray(size -> new String[size]);
package com.concretepage; import java.util.Arrays; import java.util.List; public class StreamToStringArray < public static void main(String[] args) < Listlist = Arrays.asList("Krishna", "Mahesh", "Kush"); String[] strArray = list.stream() .filter(e -> e.startsWith("K")) .toArray(size -> new String[size]); for(String s : strArray) < System.out.println(s); >> >
Example-2:
In this example we will convert stream of integer into array of integer.
StreamToIntegerArray.java
package com.concretepage; import java.util.Arrays; import java.util.List; public class StreamToIntegerArray < public static void main(String[] args) < Listlist = Arrays.asList(10, 20, 30, 40); Integer[] intArray = list.stream() .map(e -> e * 2) .toArray(Integer[]::new); for(Integer i : intArray) < System.out.println(i); >> >
The output will be 20 40 60 80.
In the above example we have used method reference. Now find the code with lambda expression.
List list = Arrays.asList(10, 20, 30, 40); Integer[] intArray = list.stream() .map(e -> e * 2) .toArray(size -> new Integer[size]);
2. Using Stream.toArray()
This method is terminal operation.
Example-1: In this example we will convert a stream of string into array of string. We know that toArray() returns Object[] , so to convert it in our required datatype, we can use Arrays.copyOf method.
Object[] objArray = Stream.of(«AA», «BB», «CC»).toArray(); String[] stArray = Arrays.copyOf(objArray, objArray.length, String[].class); for(String s : stArray)
The output will be AA BB CC.
Example-2: In this example we will convert stream of integer into array of integer.
Object[] objArray = Stream.of(10, 20, 30, 40).toArray(); Integer[] intArray = Arrays.copyOf(objArray, objArray.length, Integer[].class); for(Integer i : intArray)
3. Using IntStream.toArray()
The IntStream is the stream of int-valued elements. The IntStream.toArray() method converts stream of int values into the int array.
IntStream intStream = IntStream.of(1,2,3,4,5);
IntStream intStream = IntStream.rangeClosed(1, 5);
IntStream intStream = Stream.of(4,5,6,7,8).mapToInt(i -> i);
Now let us discuss some examples to use IntStream.toArray() method.
int[] intArray = IntStream.of(10, 20, 30, 40).toArray(); for(Integer i : intArray)
int[] intArray = IntStream.rangeClosed(10, 15).toArray(); for(Integer i : intArray)
int[] intArray = Stream.of(3,4,5,6).mapToInt(i -> i * 2).toArray(); for(Integer i : intArray)
4. Using Collectors.toList()
We can convert stream into list and then convert list into array. To convert stream into list we need to use collect(Collectors.toList()) on the stream. To convert list into array we can use List.toArray method.
StreamToListToArray.java
package com.concretepage; import java.util.stream.Collectors; import java.util.stream.Stream; public class StreamToListToArray < public static void main(String[] args) < System.out.println("--- For String ---"); String[] ar = Stream.of("Java", "Angular", "Spring") .collect(Collectors.toList()) .toArray(new String[0]); for(String e : ar) < System.out.println(e); >System.out.println("--- For Integer ---"); Integer[] intArray = Stream.of(15, 20, 30) .map(e -> e * 2) .collect(Collectors.toList()) .toArray(new Integer[0]); for(Integer i : intArray) < System.out.println(i); >> >
--- For String --- Java Angular Spring --- For Integer --- 30 40 60
Java Stream collect to array
In this post, we will see how to collect any Java 8 Stream to array.
There are many ways to do it but I am going to show easiest way.
You can simply use toArray(IntFunction generator).This generator function takes size as input and creates new array of that size.
Convert Steam to Array
Let’s understand with the help of simple example.
When you run above program, you will get below output:
It is recommended to simply use an array constructor reference as below.
Change line no. 15-16 as below.
Array constructor reference is just another way of writing aboveLambda expresssion.
Collect Stream to Integer array
If you want to convert to Integer array, you can use IntStream to do it. You can call toArray() on IntStream and it will simply convert it to int[]. You don’t need to pass any argument in this scenario.
That’s all about converting a Java stream to array in java.
Was this post helpful?
You may also like:
[Fixed] Unable to obtain LocalDateTime from TemporalAccessor
Convert LocalDate to Instant in Java
Convert Instant to LocalDate in Java
Convert String to LocalDateTime in Java
Format LocalDateTime to String in Java
Java 8 – Find duplicate elements in Stream
How to format Instant to String in java
Java Date to LocalDate
Java LocalDate to Date
Java Stream to List
Share this
Related Posts
Author
Related Posts
[Fixed] Unable to obtain LocalDateTime from TemporalAccessor
Table of ContentsUnable to obtain LocalDateTime from TemporalAccessor : ReasonUnable to obtain LocalDateTime from TemporalAccessor : FixLocalDate’s parse() method with atStartOfDay()Use LocalDate instead of LocalDateTime In this article, we will see how to fix Unable to obtain LocalDateTime from TemporalAccessor in Java 8. Unable to obtain LocalDateTime from TemporalAccessor : Reason You will generally get […]
Convert LocalDate to Instant in Java
Table of ContentsJava LocalDate to InstantUsing toInstant() wth ZoneIdUsing toInstant() with ZoneOffset In this article, we will see how to convert LocalDate to Instant in Java. Java LocalDate to Instant Instant class provides an instantaneous point in time. When you want to convert LocalDate to Instant, you need to provide time zone. Using toInstant() wth […]
Convert Instant to LocalDate in Java
Table of ContentsUsing ofInstant method [ Java 9+]Using ZoneDateTime’s toLocalDate() [Java 8] In this article, we will see how to convert Instant to LocalDate in java. Using ofInstant method [ Java 9+] Java 9 has introduced static method ofInstant() method in LocalDate class. It takes Instant and ZoneId as input and returns LocalDate object. [crayon-64c226d5627ce401570524/] […]
Convert String to LocalDateTime in Java
Table of ContentsJava String to LocalDateTimeConvert String to LocalDateTime with custom format In this article, we will see how to convert String to LocalDateTime in Java. LocalDateTime class was introduced in Java 8. LocalDateTime represents local date and time without timezone information. It is represented in ISO 8601 format (yyyy-MM-ddTHH:mm:ss) by default. Java String to […]
Format LocalDateTime to String in Java
Table of ContentsJava LocalDateTime To StringConvert LocalDateTime to Time Zone ISO8601 StringParse String to LocalDateTime In this article, we will see how to format LocalDateTime to String in java. Java LocalDateTime To String To format LocalDateTime to String, we can create DateTimeFormatter and pass it to LocalDateTime’s format() method. [crayon-64c226d56bf07838175532/] Here are steps: Get LocalDateTime […]
Java 8 – Find duplicate elements in Stream
Table of ContentsIntroductionUsing distinct()Using Collections.frequency()Using Collectors.toSet()Using Collectors.toMap()Using Collectors.groupingBy()Conclusion Introduction When working with a collection of elements in Java, it is very common to have duplicate elements, and Java provides different APIs that we can use to solve the problem. Java 8 Stream provides the functionality to perform aggregate operations on a collection, and one of […]