Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two lists of string using java stream

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

like image 735
Muhammad Naeem Shahzad Avatar asked Nov 05 '18 14:11

Muhammad Naeem Shahzad


People also ask

How do you compare two lists of strings in Java?

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.

How do you compare a field between two lists of objects?

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.

How we can compare two list in Java?

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.

What does Stream of () method in Java?

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.


2 Answers

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);
like image 53
Guy Avatar answered Nov 04 '22 07:11

Guy


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);
like image 31
Ousmane D. Avatar answered Nov 04 '22 07:11

Ousmane D.