I have two lists A and B. both have millions of elements. I want to compare and get all elements those are in list A but not in list B. Below is inefficient way to get elements.
if (!B.containsAll(A)) {
for (Integer id : A) {
if (!B.contains(id)) {
System.out.println(id);
}
}
}
I looking for an efficient way with or without streams to get elements
help is appreciated in this regards.
Thanks
Java provides a method for comparing two Array List. The ArrayList. equals() is the method used for comparing two Array List. It compares the Array lists as, both Array lists should have the same size, and all corresponding pairs of elements in the two Array lists are equal.
Java equals() method of List interface compares the specified object with the list for equality. It overrides the equals() method of Object class. This method accepts an object to be compared for equality with the list. It returns true if the specified object is equal to the list, else returns false.
You can compare two array lists using the equals() method of the ArrayList class, this method accepts a list object as a parameter, compares it with the current object, in case of the match it returns true and if not it returns false.
Stream of(T t) returns a sequential Stream containing a single element. Syntax : static Stream of(T t) Parameters: This method accepts a mandatory parameter t which is the single element in the Stream. Return Value: Stream of(T t) returns a sequential Stream containing the single specified element.
You don't need to compare
List<Integer> c = new ArrayList<>(a);
c.removeAll(b);
And if you don't mind loosing the original list data
a.removeAll(b);
Something like this should suffice:
Set<Integer> container = new HashSet<>(ListB);
ListA.stream()
.filter(id -> !container.contains(id))
.forEach(System.out::println);
or non-stream:
Set<Integer> container = new HashSet<>(ListB);
for(Integer id : ListA)
if(!container.contains(id));
System.out.println(id);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With