Search code examples
javastringjava-8java-streamcollectors

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.


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]