In this article, we will discuss how to convert Stream into a LinkedList in Java 1.8 version using Stream API
Stream to LinkedList :
- Using Collectors.toList()
- 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]
Related Articles:
- Java 8 – Conversion of Arrays to Stream
- Java 8 – Conversion of Stream to Arrays
- Java 8 – Convert List to Stream
- Java 8 – Convert Stream to List
- Java 8 – Convert Stream to ArrayList
- Java 8 – Convert Stream to LinkedList
- Java 8 – Convert Stream to HashSet
- Java 8 – Convert Stream to LinkedHashSet
- Java 8 – Convert Stream to TreeSet
References:
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toList–
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toCollection-java.util.function.Supplier-
Happy Coding !!
Happy Learning !!