1

I have Stream<SortedSet<String>>, and I want to have just a Stream<String>. I tried using flatMap() but it did not work since it cannot flat Stream of Sortedset.

String productName = "p1";
Set<Product> products = new HashSet<>();
products.add(new Product(productName));
Stream<SortedSet<String>> sortedSetStream = products.stream().map(p -> Util.getProductNames(p) );
Didier L
  • 18,905
  • 10
  • 61
  • 103
Jai
  • 131
  • 2
  • 8

1 Answers1

5

To obtain a stream of all objects from a stream of collection of those objects you need to flatten the collections. Any collection can be transformed onto a stream:

Stream<SortedSet<String>> sortedSetStream = products.stream().map(p -> Util.getProductNames(p) );
Stream<String> ss = sortedSetStream.flatMap( s -> s.stream() );

or (if you prefer method reference):

Stream<String> ss = sortedSetStream.flatMap( Collection::stream );
Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69