简体   繁体   English

拆分字符串并将唯一的字符串添加到java中的列表中

[英]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.这是一种方法。

  • Stream the list.流式传输列表。
  • split each string on the comma.在逗号上拆分每个字符串。
  • flatMap each array to single stream of words. flatMap 每个数组到单个单词流。
  • trim the white space from each word.修剪每个单词的空白区域。
  • use distinct to ignore duplicates.使用 distinct 忽略重复项。
  • assign to a list.分配给一个列表。
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM