Collectors toList() method in Java 8

Java 8Object Oriented ProgrammingProgramming

The toList() method of the Collectors class returns a Collector that accumulates the input elements into a new List.

The syntax is as follows −

static <T> Collector<T,?,List<T>> toList()

Here, parameter T is the type of input elements.

To work with Collectors class in Java, import the following package −

import java.util.stream.Collectors;

The following is an example to implement Collectors toList() method in Java −

Example

 Live Demo

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

public class Demo {
   public static void main(String[] args) {
      Stream<String> stream = Stream.of("25", "40", "90", "150", "180", "220", "350");
      List<String> list = stream.collect(Collectors.toList());
      System.out.println("List = "+list);
   }
}

Output

List = [25, 40, 90, 150, 180, 220, 350]
raja
Updated on 30-Jul-2019 22:30:25

Advertisements