Posts

Showing posts with the label Collectors.toList()

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&ltInteger&gt aList = new ArrayList&lt&gt(); // add few elements to the array list aList.add(1); aList.add(2); aList.add(3); a...

How to Convert Java 8 IntStream to a List

Image
1. Overview                     In this tutorial, we are going to convert an IntStream to List and to an array. IntStream is a stream of primitive int values and a List is an ordered collection that holds generic values. To convert a stream to the collection, we can call collect() method of Stream class, but this works when the streams hold non-primitive types. Calling collect() method on primitive streams give a compilation error "collect() in IntStream cannot be applied to". 2. Solutions 2.1. Call boxed() method before collecting to a List        IntStream has a method boxed() that returns a Stream consisting of the elements each boxed to an Integer. After getting a boxed stream, we can call the collect() method to convert into a List. Code: package streams; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; public class IntStreamTest { public stati...