Tuesday, January 18, 2022

Java Stream - Convert Stream to Array

In this tutorial you’ll see how to convert a Java Stream to Array using Stream.toArray() method.

Stream.toArray() method in Java

toArray() method is overloaded and there are two variants-

  • Object[] toArray()- Returns an array containing the elements of this stream.
  • toArray(IntFunction<A[]> generator)- Returns an array containing the elements of this stream, using the provided generator function, of type IntFunction, 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. Note that this method returns an array of the given type rather than the Object[] array so more convenient.

toArray() method Java examples

1. You can use toArray() method to convert a List of Integers to array by using list as stream source.

import java.util.Arrays;
import java.util.List;

public class StreamToArray {
  public static void main(String[] args) {
    List<Integer> strList = Arrays.asList(1, 2, 3, 4, 5, 6);
    Integer[] intArray = strList.stream()
                  .toArray(Integer[]::new);
    System.out.println("Array elements- " + Arrays.toString(intArray));
  }
}

Output

Array elements- [1, 2, 3, 4, 5, 6]

2. If you want to convert a List of Integers to an int[] then you can do that as given in the following code.

public class StreamToArray {
  public static void main(String[] args) {
    List<Integer> strList = Arrays.asList(1, 2, 3, 4, 5, 6);
    int[] intArray = strList.stream().mapToInt(e -> e)
                  .toArray();
    System.out.println("Array elements- " + Arrays.toString(intArray));
  }
}

3. Using toArray() with custom objects. For the example Employee class is used.

Employee class

public class Employee {
  private String empId;
  private int age;
  private String name;
  private char gender;
  private int salary;
  Employee(String empId, int age, String name, char gender, int salary){
    this.empId = empId;
    this.age = age;
    this.name = name;
    this.gender = gender;
    this.salary = salary;
  }
  public String getEmpId() {
    return empId;
  }

  public int getAge() {
    return age;
  }

  public String getName() {
    return name;
  }

  public char getGender() {
    return gender;
  }

  public int getSalary() {
    return salary;
  }
  @Override
  public String toString() {
    return "Emp Id: " +  getEmpId() + " Name: " + getName() + " Age: " + getAge();
  }
}

If you want to collect Employee objects with age greater than 30 into an array.

public class StreamToArray {
  public static void main(String[] args) {
    List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                new Employee("E002", 35, "Shelly", 'F', 7000), 
                new Employee("E003", 24, "Mark", 'M', 9000), 
                new Employee("E004", 37, "Ritu", 'F', 11000),
                new Employee("E005", 32, "Anuj", 'M', 12000), 
        new Employee("E006", 28, "Amy", 'F', 14000)); 
    
    Employee[] employeeArray = empList.stream()
         .filter(e->e.getAge() > 30)
         .toArray(Employee[]::new);
    
    System.out.println(Arrays.toString(employeeArray));
  }
}

Output

[Emp Id: E001 Name: Ram Age: 40, Emp Id: E002 Name: Shelly Age: 35, Emp Id: E004 Name: Ritu Age: 37, 
Emp Id: E005 Name: Anuj Age: 32]

That's all for this topic Java Stream - Convert Stream to Array. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - Convert Stream to Set
  2. Java Stream - Convert Stream to Map
  3. Java Stream - sorted() With Examples

You may also like-

  1. Why wait(), notify() And notifyAll() Must be Called Inside a Synchronized Method or Block
  2. Interface Default Methods in Java
  3. static Reference to The Non-static Method or Field Error
  4. How to Create Password Protected Zip File in Java
  5. Java Concurrency Interview Questions And Answers
  6. Spring Object XML Mapping (OXM) JAXB Example
  7. Named Tuple in Python
  8. Converting Text File to Parquet File Using Hadoop MapReduce

No comments:

Post a Comment