How to Convert Java 8 IntStream to a List
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:
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 static void main(String[] args) { List<integer> intList = IntStream.of(10, 20, 30, 40). boxed(). collect(Collectors.toList()); System.out.println(intList); } }
Result:
2.2. Call mapToObj() method before collecting to a List
IntStream has a method mapToObj() that returns an object-valued Stream. Calling this method we can manually box the primitive integer into Integer object. After this 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 static void main(String[] args) { List<integer> intList = IntStream.of(10, 20, 30, 40). mapToObj(Integer::valueOf). collect(Collectors.toList()); System.out.println(intList); } }
Result:
3. Conclusion
In this tutorial, we have seen 2 ways of converting an IntStream to a List using methods provided by IntStream.
In this tutorial, we have seen 2 ways of converting an IntStream to a List using methods provided by IntStream.
Comments
Post a Comment