Java Stream How to - Convert String to TreeSet








Question

We would like to know how to convert String to TreeSet.

Answer

/*ww  w .  j av  a  2 s  .c  o m*/
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    // collect as typed array
    Stream<String> words = Stream.of("All", "men", "are", "created", "equal");
    Set<String> wordsSet = words.collect(Collectors.toCollection(TreeSet::new));

    wordsSet.forEach(n -> System.out.println(n));
  }
}

The code above generates the following result.