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.
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.