In Detail:Collectors toList() method in Java 8

Introduction:

         Collectors.toList() method is used to transform the java stream into a List of values. This process is called a reduction. The Collectors class implements various useful reduction operations such as accumulating the stream elements into collections etc. 
In a simple layman terms, Collectors.toList() method is used to convert a stream of values to a List of values.

Collectors.toList() actually returns a Collector object which accumulates/combines the input elements into a new List. 

Now let us see how to implement Collectors.toList() with an example.

Code Exmaple

package test;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class CollectorsToList {

 public static void main(String[] args) {

  // create a sample list
  List<Integer> aList = new ArrayList<>();

  // add few elements to the array list
  aList.add(1);
  aList.add(2);
  aList.add(3);
  aList.add(4);
  aList.add(5);
  aList.add(10);
  aList.add(11);
  aList.add(15);
  aList.add(20);
  aList.add(25);

  // step 1 : filter the values greater than 10
  // step 2 : Collect to a new list using Collectors.toList
  List<Integer> listGreaterThan10 = aList.stream().filter(i -> (i > 10)).collect(Collectors.toList());

  // print the list to console finally
  System.out.println(listGreaterThan10);
 }

}

When to use Collectors.toList()

In the above example, I used Collectors.toList() method after I have filtered the stream to have values greater than 10. If you want to convert a stream into a List, then you can simply use Collectors.toList() method.

Comments