How to convert Stream to TreeSet in Java?

Java 8Object Oriented ProgrammingProgramming

Let us first create a Stream:

Stream<String> stream = Stream.of("UK", "US", "India", "Australia", "Armenia", "Canada", "Poland");

Now convert Stream to TreeSet:

Set<String> set = stream.collect(Collectors.toCollection(TreeSet::new));

The following is an example to convert String to TreeSet in Java:

Example

import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      Stream<String> stream = Stream.of("UK", "US", "India", "Australia", "Armenia", "Canada", "Poland");
      Set<String> set = stream.collect(Collectors.toCollection(TreeSet::new));
      set.forEach(val -> System.out.println(val));
   }
}

Output

Armenia
Australia
Canada
India
Poland
UK
US
raja
Published on 02-May-2019 08:23:04
Advertisements