0

Requirement: Please consider a function which generates List<List<String>> and return the same.

So in Java 1.7, this can be considered as:

public List<List<String> function(){
  List<List<String>> outList = new ArrayList<>();
  List<String> inList = new ArrayList<>();
  inList.add("ABC");
  inList.add("DEF");
  outList.add(inList);
  outList.add(inList);
  return outList;
}

Now in Java 8, the signature of the function provided to me is:

public Stream<Stream<String>> function() {
      List<List<String>> outList = new ArrayList<>();
      List<String> inList = new ArrayList<>();
      inList.add("ABC");
      inList.add("DEF");
      outList.add(inList);
      outList.add(inList);
      //How to convert the outList into Stream<Stream<String>> and return.
}

How to convert List<List<String>> into Stream<Stream<String>>.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Pratim Singha
  • 569
  • 2
  • 10
  • 33
  • 6
    Answer by @YCF_L will do the work, but I have another question: why do you want to return `Stream>` if you're asked to - *Please consider a function which generates List> and return the same.* ? – Giorgi Tsiklauri Oct 19 '20 at 16:58
  • The function signature provided to me are like `public Stream> function() { return Stream.of() }` But as of now, since I am not comfortable in Streams, I have worked it out with List> – Pratim Singha Oct 19 '20 at 17:02
  • 1
    Returning a `Stream` is a *bad idea*. You have no idea what the state of the stream is. The caller doesn't even know if they can iterate the stream at all. If you pass Streams around, everyone can break anyone elses code just by using the Stream! – Polygnome Oct 19 '20 at 17:06
  • @Polygnome I think it is not that bad in some situations, instead, it can be the right choice, read this, [Should I return a Collection or a Stream?](https://stackoverflow.com/questions/24676877/should-i-return-a-collection-or-a-stream) – Youcef LAIDANI Oct 19 '20 at 17:12

1 Answers1

1

How to convert List<List<String>> into Stream<Stream<String>>:

You need just to this :

return outList.stream()
        .map(List::stream);

Or another way without using Lists, you can use :

public Stream<Stream<String>> function() {
    Stream<String> inList = Stream.of("ABC", "DEF");
    return Stream.of(inList, inList);
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • That have worked. But for learning, what is the return statement is like `return Stream.of` How to make that into Stream> – Pratim Singha Oct 19 '20 at 16:59