[英]Split string and add unique strings to list in java
I have the following list of strings containing words.我有以下包含单词的字符串列表。
List<String> words = new ArrayList();
words.add("hello, hi, henry");
words.add("hello1, hi1, henry1");
words.add("hello, hi, henry");
How can I loop through the words list, extract each element separated by a comma and generate a new list with unique elements.如何遍历单词列表,提取由逗号分隔的每个元素并生成具有唯一元素的新列表。 Output list should contain only the unique elements from the original list: hello, hi, henry, hello1, hi1, henry1.输出列表应仅包含原始列表中的唯一元素:hello、hi、henry、hello1、hi1、henry1。 Wondering if there is an easier way to do this using streams in java 8 Thank you.想知道是否有更简单的方法来使用 java 8 中的流来做到这一点 谢谢。
Here is one approach.这是一种方法。
List<String> result = words.stream()
.flatMap(str -> Arrays.stream(str.split(",")))
.map(String::trim).distinct().toList();
System.out.println(result);
Prints印刷
[hello, hi, henry, hello1, hi1, henry1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.