Java 8 – Convert Stream to LinkedList

In this article, we will discuss how to convert Stream into a LinkedList in Java 1.8 version using Stream API

Stream to LinkedList :

  1. Using Collectors.toList()
  2. Using Collectors.toCollection()

1. Using Collectors.toList()

  • First, convert Stream to List using collect() method of Stream API by passing Collectors.toList() as input argument
  • Above conversion yields List and not LinkedList
  • For List to LinkedList conversion, create LinkedList object and pass above list as constructor-argument
  • Finally, print converted LinkedList elements to console

StreamToLinkedListUsingCollectorsToList.java

package net.bench.resources.stream.to.list;

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

public class StreamToLinkedListUsingCollectorsToList {

	public static void main(String[] args) {

		// 1. Stream of String tokens
		Stream<String> nameStream = Stream.of(
				"Rajiv",
				"Anbu",
				"Santosh",
				"Abdul",
				"Lingaraj"
				);


		// 2. convert Stream<String> to List<String>
		List<String> names = nameStream.collect(Collectors.toList());


		// 3. List<String> to LinkedList<String>
		LinkedList<String> alNames = new LinkedList<String>(names);


		// 4. print to console
		System.out.println("Stream to LinkedList : \n\n" + alNames);
	}
}

Output:

Stream to LinkedList : 

[Rajiv, Anbu, Santosh, Abdul, Lingaraj]

2. Using Collectors.toCollection()

  • Convert Stream to LinkedList using collect() method of Stream API by passing Collectors.toCollection(LinkedList::new) as input argument directly
  • Print converted LinkedList elements to console

StreamToLinkedListUsingCollectorsToCollection.java

package net.bench.resources.stream.to.list;

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

public class StreamToLinkedListUsingCollectorsToCollection {

	public static void main(String[] args) {

		// 1. Stream of String tokens
		Stream<String> nameStream = Stream.of(
				"Rajiv",
				"Anbu",
				"Santosh",
				"Abdul",
				"Lingaraj"
				);


		// 2. convert Stream<String> to List<String>
		LinkedList<String> names = nameStream
				.collect(Collectors.toCollection(LinkedList::new));


		// 3. print to console
		System.out.println("Stream to LinkedList : \n\n" + names);
	}
}

Output:

Stream to LinkedList : 

[Rajiv, Anbu, Santosh, Abdul, Lingaraj]

References:

Happy Coding !!
Happy Learning !!

Java 8 - Convert Stream to HashSet
Java 8 - Convert Stream to ArrayList