How can I get a list of objects that are not in 2 lists?
Example: the requested result is:
List1: [1, 2, 3, 4] List2: [2, 3, 4, 5] Diffs: [1, 5]
This code works, but can you give a more elegant solution?
public class ListDifferenceDemo {
public static void main(String[] args) {
List<Integer> list1 = List.of(1, 2, 3, 4);
List<Integer> list2 = List.of( 2, 3, 4, 5);
List<Integer> diffs = new ArrayList<>(Stream.concat(list1.stream(), list2.stream()).toList());
List<Integer> subset =new ArrayList<>( list1);
subset.retainAll( list2);
diffs.removeAll( subset);
System.out.println( "List1: " + list1);
System.out.println( "List2: " + list2);
System.out.println( "Diffs: " + diffs);
}
}
1