How do I use Collectors.toCollection() method?

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 new TreeSet.
  • The method referenced by TreeSet::new is a constructor reference that creates a new empty TreeSet.

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.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.