Stunner
Stunner

Reputation: 1171

check number of elements in list A present in list B java

I have two lists (arraylists) and I would like to know effective way to check number of elements of List A present in List B.

List<String> listA = new ArrayList<>();
List<String> listB = new ArrayList<>();

I would like to know how many elements in listA are present in listB

I can loop over and check but I am looking for an effective and fastest way I can do using java 1.8

Thanks for help.

Upvotes: 2

Views: 535

Answers (4)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60046

You can create third list which contain the same content of listA, then remove listB from the new list and then you can distinct how many elements in listA are present in listB like this:

List<String> listC = new ArrayList<>(listA);
listC.removeAll(listB);
int elementsPresentInListB = listA.size() - listC.size();

Upvotes: 1

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

All you need to do is just to find the size of the set intersection. You can create a set from listB. Then iterate over each element in listA and check for it's containment in the set. The set contains takes O(1) time for a hash-based set. So, this takes O(n) time and space complexity. Here's how it looks.

final Set<String> setB = new HashSet<>(listB);
int c = 0;
for (String string : listA)
    if (setB.contains(string))
        c = c + 1;

A more succinct solution would be:

setB.retainAll(listA);
c = setB.size();

This operation effectively modifies this set so that its value is the intersection of the two sets.

Upvotes: 0

maloomeister
maloomeister

Reputation: 2486

Using Java 8's Stream API, you can use the following to get the intersection of your two lists:

Set<String> intersection = listA.stream()   // creates stream
                                .distinct() // filters out any duplicates
                                .filter(listB::contains) // filters the intersection
                                .collect(Collectors.toSet()); // reduces to set
int amount = intersection.size(); // your amount of duplicate elements

Upvotes: 0

akourt
akourt

Reputation: 5573

Another easy approach without looping and without creating a third list could be the following:

var listA = new ArrayList<>(list1);
var listB = new ArrayList<>(list2);
listB.retainAll(listA);
System.out.println(listB);

Note that this approach assumes that there are no duplicates in the list but should this be the case, you can simply create two sets out of the lists on hand and apply the same approach.

Upvotes: 4

Related Questions