Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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. Wondering if there is an easier way to do this using streams in java 8 Thank you.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here is one approach.

  • Stream the list.
  • split each string on the comma.
  • flatMap each array to single stream of words.
  • trim the white space from each word.
  • use distinct to ignore duplicates.
  • 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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading