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.
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]