The Collectors.toCollection()
method is a static method in the java.util.stream.Collectors
class of Java 8. This method is used with streams when you want to convert a list to another collection type.
Here’s a simple example of how to use the method:
package org.kodejava.stream;
import java.util.*;
import java.util.stream.Collectors;
public class CollectorsToCollection {
public static void main(String[] args) {
List<String> list =
Arrays.asList("Java", "Kotlin", "Python", "Scala", "Kotlin");
// Convert List to TreeSet
TreeSet<String> treeSet = list.stream()
.collect(Collectors.toCollection(TreeSet::new));
System.out.println(treeSet);
}
}
Output:
[Java, Kotlin, Python, Scala]
In this code:
- We have a List of Strings.
- We convert this list into a
TreeSet
. Collectors.toCollection(TreeSet::new)
is the collector that collects the data from the stream into a newTreeSet
.- The method referenced by
TreeSet::new
is a constructor reference that creates a new emptyTreeSet
.
The output of the program will be the TreeSet
containing the elements of the list.
Keep in mind that a TreeSet
automatically orders its elements (in this case, alphabetically since the elements are Strings) and does not allow duplicates. So, if the list had duplicate values, and you wanted to maintain them in your new collection, you would need to choose a different type of Set
or use a List
.
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024