Java basic learning summary (206) - Compare the differences between two Lists

method one

  1. Convert two Lists to Stream type;

  2. Call the filter method of Stream to filter out different objects;

  3. Convert the filtered different objects into List type.

List<String> list1 = Arrays.asList("A", "B", "C", "D");
List<String> list2 = Arrays.asList("B", "C", "E", "F", "A", "D");
List<String> diff = list1.stream().filter(item -> !list2.contains(item)).collect(Collectors.toList());
List<String> diff1 = list2.stream().filter(item -> !list1.contains(item)).collect(Collectors.toList());
diff.addAll(diff1);

diff.forEach(x -> System.out.println(x));

In the above code, two List type objects list1 and list2 are converted into Stream type, and the filter method is called to filter out different objects. Finally, the different objects are converted into List types through the collect method, and the results are output.

Method 2

List<String> list1 = Arrays.asList("apple", "banana", "orange", "pear

Guess you like

Origin blog.csdn.net/u012562943/article/details/132262759