When working with collections in Java, a common task is figuring out what’s different between two lists. Maybe you’re syncing data, comparing results, or just trying to identify what’s missing or extra.
In this article, we’ll walk through different ways to find:
- Elements present in List A but not in List B
- Elements present in List B but not in List A
- Elements that are common to both lists
- Elements that are in either list, but not in both
We’ll cover solutions using:
- ✅ Core Java
- 🌟 Java 8+ Streams
- 🔧 Google Guava
- 🧰 Apache Commons Collections
1. Using Core Java
Use the methods removeAll() and retainAll() of the List interface.
Example:
import java.util.*;
public class ListOperations {
public static void main(String[] args) {
List<String> listA = new ArrayList<>(Arrays.asList("apple", "banana", "coconut", "dates"));
List<String> listB = new ArrayList<>(Arrays.asList("banana", "dates", "fig", "grape"));
List<String> presentOnlyInA = new ArrayList<>(listA);
presentOnlyInA.removeAll(listB);
System.out.println("Only in A: " + presentOnlyInA);
// B - A
List<String> presentOnlyInB = new ArrayList<>(listB);
presentOnlyInB.removeAll(listA);
System.out.println("Only in B: " + presentOnlyInB);
// A ∩ B ( Interesection)
List<String> common = new ArrayList<>(listA);
common.retainAll(listB);
System.out.println("Common: " + common);
}
}
Code language: PHP (php)
Output
Only in A: [apple, coconut]
Only in B: [fig, grape]
Common: [banana, dates]
Code language: CSS (css)
This is a simple approach using just the core Java without any external dependencies.
2. Using Java 8+ Streams
Java streams offer a neat, simpler, and functional way to compare lists using the filter() function. My personal preference is to use this approach as it is more expressive and follows a functional programming style.
import java.util.*;
import java.util.stream.Collectors;
public class ListOperationsUsingStreams {
public static void main(String[] args) {
List<Integer> listA = Arrays.asList(1, 2, 3, 4, 5,9);
List<Integer> listB = Arrays.asList(4, 5, 6, 7,9,10);
List<Integer> presentOnlyInA = listA.stream()
.filter(e -> !listB.contains(e))
.collect(Collectors.toList());
List<Integer> presentOnlyInB = listB.stream()
.filter(e -> !listA.contains(e))
.collect(Collectors.toList());
List<Integer> common = listA.stream()
.filter(listB::contains)
.collect(Collectors.toList());
List<Integer> notPresentInBoth = new ArrayList<>();
notPresentInBoth.addAll(presentOnlyInA);
notPresentInBoth.addAll(presentOnlyInB);
System.out.println("Only in A: " + presentOnlyInA);
System.out.println("Only in B: " + presentOnlyInB);
System.out.println("Common: " + common);
System.out.println("Not Present in both lists: " + notPresentInBoth);
}
}
Code language: PHP (php)
Output
Only in A: [1, 2, 3]
Only in B: [6, 7, 10]
Common: [4, 5, 9]
Not Present in both lists: [1, 2, 3, 6, 7, 10]
Code language: CSS (css)
3. Using Google Guava
Google Guava’s Sets.difference() and Sets.symmetricDifference() make this super concise, especially for Set operations.
Maven dependency:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>32.1.2-jre</version>
</dependency>
Code language: HTML, XML (xml)
package com.thestembook;
import com.google.common.collect.Sets;
import java.util.*;
public class GuavaListOperations {
public static void main(String[] args) {
Set<String> setA = new HashSet<>(Arrays.asList("mobile", "tv", "laptop"));
Set<String> setB = new HashSet<>(Arrays.asList("desktop", "tv", "mobile"));
Set<String> onlyInA = Sets.difference(setA, setB);
Set<String> onlyInB = Sets.difference(setB, setA);
Set<String> nonCommon = Sets.symmetricDifference(setA, setB);
System.out.println("Only in A: " + onlyInA);
System.out.println("Only in B: " + onlyInB);
//elements present only in a single set. Common elements are removed.
System.out.println("Not in both sets " + nonCommon);
}
}
Code language: JavaScript (javascript)
Using Apache Commons Collections
Use CollectionUtils of Apache Commons for list operations. Methods subtract() , intersection(), disjunction()
package com.thestembook;
import org.apache.commons.collections4.CollectionUtils;
import java.util.*;
public class ApacheCommonsListOperations {
public static void main(String[] args) {
List<String> listA = Arrays.asList("1", "2", "3", "4");
List<String> listB = Arrays.asList("3", "2", "5", "6");
Collection<String> presentOnlyInA = CollectionUtils.subtract(listA, listB);
Collection<String> presentOnlyInB = CollectionUtils.subtract(listB, listA);
Collection<String> commonToBoth = CollectionUtils.intersection(listA, listB);
Collection<String> nonCommon = CollectionUtils.disjunction(listA,listB);
System.out.println("Only in A: " + presentOnlyInA);
System.out.println("Only in B: " + presentOnlyInB);
System.out.println("Common: " + commonToBoth);
System.out.println("Non Common: " + nonCommon);
}
}
Code language: JavaScript (javascript)
Conclusion
We have explored the different ways to find the difference between two lists. There is no better choice, as it depends on the use case and whether the project is already using a library. In my opinion, better choice is to follow the options available in core java and that too with java streams.
Leave a Reply