1

I need to find the difference between the two string Array list using java 8 features . Current i am doing it like this

final List<String> a = new ArrayList<>();
        a.add("1");
        a.add("2");
        a.add("3");

        final List<String> b = new ArrayList<>();
        b.add("1");
        b.add("2");
        b.add("4");

        final List<String> result = a.stream().filter((s) -> b.stream().noneMatch(s::equals))
                .collect(Collectors.toList());
        final List<String> result2 = b.stream().filter((s) -> a.stream().noneMatch(s::equals))
                .collect(Collectors.toList());

        System.out.println(result);
        System.out.println(result2);

        final List<String> FinalResult = java.util.stream.Stream.concat(result.stream(), result2.stream())
                .distinct()
                .collect(Collectors.toList());   

        System.out.println(FinalResult);

Can any one suggest a cleaner and shorter code for the same thing ? I am feeling it can be done in some other simpler way .

user_531
  • 241
  • 4
  • 15

1 Answers1

3

You can do the same thing using below code:

List<String> result = b.stream()
                       .filter(not(new HashSet<>(a)::contains))
                       .collect(Collectors.toList());

private static <T> Predicate<T> not(Predicate<T> predicate) {
    return predicate.negate();
}

Hope it helps.

Oleksandr Pyrohov
  • 14,685
  • 6
  • 61
  • 90
Antariksh
  • 508
  • 8
  • 17