Java 8 – Convert IntStream to List and Others – Java Code Geeks

I show You how To Make Huge Profits In A Short Time With Cryptos!

A quick guide on how to convert IntStream to List in java 8.

1. Overview

In this tutorial, we will learn how to convert IntStream to the list in java 8 and java 16 versions above.

IntStream is used for create infinite streams in java 8 and it has the method to convert it to an array using
toArray () method.

But there is no other way to convert it directly to List or set.

Converting IntStream to a list can be done in two ways.

2. Java 8 – IntStream to list or set

In the java 8 API, the IntStream class has framed () method. The boxed () method converts primitive int values ​​into a stream of whole objects.

Once we get the Flux instance, we can convert it to list, set or card or any collection.

Example 1

package com.javaprogramto.java8.intstream.toList;

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

public class IntStreamToListExample {

	public static void main(String[] args) {

		IntStream evenIntStream = IntStream.iterate(0, i -> i + 2);

		Stream<Integer> stream = evenIntStream.limit(100).boxed();

		List<Integer> list = stream.collect(Collectors.toList());

		System.out.println("list size : " + list.size());

		IntStream evenIntStream2 = IntStream.iterate(0, i -> i + 2);
		
		Stream<Integer> stream2 = evenIntStream2.limit(100).boxed();

		List<Integer> linkedList = stream2.collect(Collectors.toCollection(LinkedList::new));

		System.out.println("linkedList size : " + linkedList.size());

	}
}

Go out

list size : 100
linkedList size : 100

3. Java 16 – IntStream to list or define

JDK 16 is added with the list () method in Stream api. but the returned list is a unchangeable listing.

Example 2

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

public class IntStreamToListExample2 {

	public static void main(String[] args) {

		IntStream evenIntStream = IntStream.iterate(0, i -> i + 2);

		List<Integer> list = evenIntStream.limit(100).boxed().toList();

		System.out.println("list size : " + list.size());
	}
}

Go out:

list size : 100

4. Conclusion

In this article we have seen how to convert InstStream to a Collection object in Java 8 and 16 versions.

GitHub

Stream.toList ()



Source link