我有一个列表,其中包含逗号分隔的值作为单个元素。喜欢:
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]]
答案 0 :(得分:3)
您的.map(item->item.split(","))
步骤将Stream<String>
转换为Stream<String[]>
。由于您将每个元素映射到多个元素,因此应使用flatMap
以获得所有这些元素的平面Stream<String>
,以后可以将其收集到Set
中。
在将逗号分隔的Set
拆分之后,您似乎想要一个String
的所有唯一元素:
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));