Java List Comparison Guide
One way to compare the differences between two lists is by using the Java Stream API.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> list1 = new ArrayList<>();
list1.add("A");
list1.add("B");
list1.add("C");
List<String> list2 = new ArrayList<>();
list2.add("B");
list2.add("C");
list2.add("D");
List<String> added = list2.stream()
.filter(e -> !list1.contains(e))
.collect(Collectors.toList());
List<String> removed = list1.stream()
.filter(e -> !list2.contains(e))
.collect(Collectors.toList());
System.out.println("Added elements: " + added);
System.out.println("Removed elements: " + removed);
}
}
In this example, we initially create two Lists, list1 and list2. We then use the Stream API and collect() method to identify the elements added to list2 and removed from list1, and finally print out these elements.