【问题标题】:Is there a way to convert steam.map() individual output to list有没有办法将 steam.map() 单个输出转换为列表
【发布时间】:2019-10-29 13:28:49
【问题描述】:

我有一个包含逗号分隔值作为单个元素的列表。喜欢:

   List<String> personOutputList=new ArrayList<>();
   personOutputList.add("nexus 9k, nexus 9000,n9k");
   personOutputList.add( "nexus 7k, nexus 7000,n7k");
   personOutputList.add("nexus 9000");
   personOutputList.add("utility issue");
   personOutputList.add("network availability issue");
   personOutputList.add("nexus 7000");
   personOutputList.add("nexus 9k issue");

是否可以将逗号分隔的元素转换为单独元素列表的一部分,例如:

[nexus 9k、nexus 9000、n9k、nexus 7k、nexus 7000、n7k、nexus 9000、实用程序问题、网络可用性问题、nexus 7000、nexus 9k 问题]

outputSet=outputSet.stream()
  .map(item->item.split(","))
  .collect(Collectors.toCollection(HashSet::new));

但它返回String[]字符串数组,我想作为List元素

[nexus 9k、nexus 9000、n9k、nexus 7k、nexus 7000、n7k、nexus 9000、实用程序问题、网络可用性问题、nexus 7000、nexus 9k 问题]

我需要这样的输出: 套装包含:[nexus 7000、nexus 7k、nexus 7000、n7k、nexus 9k、n9k、nexus 9000、nexus 9k 问题、实用程序问题、网络可用性问题]

不是这样的: 套装包含什么? :[[nexus 7k,nexus 7000,n7k],[nexus 9k,nexus 9000,n9k]]

【问题讨论】:

  • 如果你想要一个列表,那么让你的流表达式以.collect(Collectors.toList());结尾,但是对于唯一值,使用Set。
  • 您是否希望在输出中包含重复项(因为“nexus 9000”出现两次)?如果你这样做了,你为什么要创建一个不允许重复的Set?
  • 不,我想要一个唯一的值,将编辑我的问题

标签: java list dictionary


【解决方案1】:

您的.map(item-&gt;item.split(",")) 步骤将Stream&lt;String&gt; 转换为Stream&lt;String[]&gt;。由于您将每个元素映射为多个元素,因此您应该使用flatMap 来获得所有这些元素的平面Stream&lt;String&gt;,以后可以将其收集到Set 中。

在拆分逗号分隔的Strings 之后,您似乎想要一个包含所有唯一元素的Set:

Set<String> outputSet = 
    personOutputList.stream()
                    .flatMap(s -> Arrays.stream(s.split(","))
                    .collect(Collectors.toSet());

或者,如果您想确保获得HashSet:

HashSet<String> outputSet = 
    personOutputList.stream()
                    .flatMap(s -> Arrays.stream(s.split(","))
                    .collect(Collectors.toCollection(HashSet::new));

【讨论】:

  • 谢谢,我不知道 flatMap。这对我帮助很大。
猜你喜欢
  • 1970-01-01
  • 2021-03-01
  • 2011-01-12
  • 2022-07-06
  • 2019-01-31
  • 2019-10-03
  • 2011-02-02
  • 1970-01-01
  • 2020-05-02
相关资源
最近更新 更多