Here we will see how to convert Java 8 Stream to Array of strings or objects.
Convert Java 8 Stream to Array:
The easiest way to convert the Java 8 stream to Array is to use the toArray(IntFunction<A[]> generator).
1. Stream of Strings into String Array:
Create a stream of strings and use the toArray() method on stream to convert into Array.
// Stream of Strings to String[]
Stream<String> stringStream = Stream.of("JAVA", "SPRING", "HIBERNATE");
String[] stringArray = stringStream.toArray(String[]::new);
Arrays.stream(stringArray).forEach(System.out::println);
// Or using size
Stream<String> stringStream2 = Stream.of("JAVA", "SPRING", "HIBERNATE");
stringArray = stringStream2.toArray(size -> new String[size]);
Arrays.stream(stringArray).forEach(System.out::println);
Output:
Terminal
JAVA
SPRING
HIBERNATE
2. Stream of ints to int Array:
Creating a stream of ints from 1 to 10 using IntSteam and converting it into int array using a mapToInt() method.
Stream<Integer> intStream = IntStream.rangeClosed(1, 10).boxed();
int[] array = intStream.mapToInt(x -> x).toArray();
Arrays.stream(array).forEach(System.out::println);
3. Stream of Objects into Object Array:
Creating Stream of Book objects using Stream.of() method and converting it into Object[] using toArray() method.
Book class:
Book.java
public class Book {
private int id;
private String name;
private double price;
public Book(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
'}';
}
}
Converting Stream<Book> to Object[]
// Stream of Objects to Array of objects
Stream<Book> objectStream = Stream.of(new Book(1,"Thinking in Java",1500),
new Book(2,"Inide Java Vertual Machine",570));
Object[] stringArray2 = objectStream.toArray(Object[]::new);
Arrays.stream(stringArray2).forEach(System.out::println);
Output:
Terminal
Book{id=1, name='Thinking in Java', price=1500.0}
Book{id=2, name='Inide Java Vertual Machine', price=570.0}
4. References:
Happy Learning 🙂