June 29, 2022

Convert Java Stream to Array - toArray() method

In this tutorial you’ll see how to convert a Stream to array using toArray() method of the Java Stream API.

Java Stream toArray() method

There are two overloaded toArray() methods-

  • Object[] toArray()- Returns an array containing the elements of this stream.
  • toArray(IntFunction<A[]> generator)- This method also returns an array containing the elements of this stream. In this method a generator function of type IntFunction is passed 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. This method returns an array of the given type rather than the Object[] array so it is a more preferred method.

Stream API toArray() Java examples

1. In the first example we’ll be converting a list of Strings into array of Strings using toArray method.

public class StreamToArray {

  public static void main(String[] args) {
    List strList = Arrays.asList("A", "B", "C", "D", "E");
    String[] strArray = strList.stream()
[A, B, C, D, E]

2. You can also collect Stream element into an array to get an array of custom objects.

For the example Student class’ objects are used which is defined as given below.

Student class used is as follows-

public class Student {
  private int rollNo;
  private String name;
  private String stream;
  private int marks;
  Student(int rollNo, String name, String stream, int marks){
    this.rollNo = rollNo;
    this.name = name;
    this.stream = stream;
    this.marks = marks;
  public int getRollNo() {
    return rollNo;
  public String getName() {
    return name;

  public String getStream() {
    return stream;

  public int getMarks() {
    return marks;

  public String toString() {
    return "Roll Number: " +  getRollNo() 
        + " Name: " + getName() + " Marks: " + getMarks();

If you want to collect only those student objects who have scored more than 90 into an array.

public class StreamToArray {

  public static void main(String[] args) {
    List<Student> studentList = Arrays.asList(new Student(1, "Mercy", "Science", 75),
              new Student(2, "Ram", "Science", 99),
              new Student(3, "Priscilla", "Art", 68),
              new Student(4, "Jacques", "Maths", 97),
              new Student(5, "Peter", "Science", 75));
    Student[] studentArray = studentList.stream()
                  .filter(s->s.getMarks() > 90)
    for(Student s : studentArray) {
Roll Number: 2 Name: Ram Marks: 99
Roll Number: 4 Name: Jacques Marks: 97

That's all for the topic Convert Stream to Array - toArray() method. If something is missing or you have something to share about the topic please write a comment.

You may also like

No comments:

Post a Comment