Search code examples
javajava-8java-streamcollect

Java 8 code to concatenate a List of Strings without duplicates


I have a Hit class and a List<Hit> that contains something like this:

{{id=1, list="EU"}, {id=2, list="EU,OF,UN"}}

How can I get some concatenated lists without doubled occurrences?

I tried something like this:

Set<String> sourceList = alertHit.stream()
                .map(Hit::getList)
                .collect(Collectors.toSet());

but I get "EU, EU,OF,UN" in my sourceList Set. How can I get only "EU,OF,UN" in my Set? Thanks!


Solution

  • If Hit::getList returns a String of comma separated elements, you have to split that String.

    This will produce a String[] which can be used to produce a Stream<String>.

    Finally, you need to use flatMap instead of map in order to get a flat Stream of all those Strings. That's the Stream you should collect into a Set.

    Set<String> sourceList = 
        alertHit.stream()
                .flatMap(h -> Arrays.stream(h.getList().split(",")))
                .collect(Collectors.toSet());