Convert List< List< String>> to Stream< Stream< String>>

huangapple go评论68阅读模式
英文:

Convert List<List<String>> to Stream<Stream<String>>

问题

Requirement:
请考虑一个生成 `List<List<String>>` 并返回相同的函数

所以在 Java 1.7可以考虑如下

    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;
    }

现在在 Java 8 中我提供的函数签名是

    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);
          //如何将 outList 转换为 Stream<Stream<String>> 并返回。
    }

如何将 `List<List<String>>` 转换为 `Stream<Stream<String>>`。
英文:

Requirement:
Please consider a function which generates List&lt;List&lt;String&gt;&gt; and return the same.

So in Java 1.7, this can be considered as:

public List&lt;List&lt;String&gt; function(){
  List&lt;List&lt;String&gt;&gt; outList = new ArrayList&lt;&gt;();
  List&lt;String&gt; inList = new ArrayList&lt;&gt;();
  inList.add(&quot;ABC&quot;);
  inList.add(&quot;DEF&quot;);
  outList.add(inList);
  outList.add(inList);
  return outList;
}

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

public Stream&lt;Stream&lt;String&gt;&gt; function() {
      List&lt;List&lt;String&gt;&gt; outList = new ArrayList&lt;&gt;();
      List&lt;String&gt; inList = new ArrayList&lt;&gt;();
      inList.add(&quot;ABC&quot;);
      inList.add(&quot;DEF&quot;);
      outList.add(inList);
      outList.add(inList);
      //How to convert the outList into Stream&lt;Stream&lt;String&gt;&gt; and return.
}

How to convert List&lt;List&lt;String&gt;&gt; into Stream&lt;Stream&lt;String&gt;&gt;.

答案1

得分: 1

> 如何将 List&lt;List&lt;String&gt;&gt; 转换为 Stream&lt;Stream&lt;String&gt;&gt;

你只需要这样做:

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

或者另一种方式,不使用列表,你可以这样做:

public Stream&lt;Stream&lt;String&gt;&gt; function() {
    Stream&lt;String&gt; inList = Stream.of("ABC", "DEF");
    return Stream.of(inList, inList);
}
英文:

> How to convert List&lt;List&lt;String&gt;&gt; into Stream&lt;Stream&lt;String&gt;&gt;:

You need just to this :

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

Or another way without using Lists, you can use :

public Stream&lt;Stream&lt;String&gt;&gt; function() {
    Stream&lt;String&gt; inList = Stream.of(&quot;ABC&quot;, &quot;DEF&quot;);
    return Stream.of(inList, inList);
}

huangapple
  • 本文由 发表于 2020年10月20日 00:51:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/64431860.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定