Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList contains one or more entities from another ArrayList [duplicate]

I have two ArrayLists (list1 & list2). I would like to see if any 1 (or more) of the objects in list2(which are strings) occur in list1.

So, for some examples:

List<String> list1 = Arrays.asList("ABCD", "EFGH", "IJKL", "QWER");
List<String> list2 = Arrays.asList("ABCD", "1234");
//Should result in true, because "ABCD" is in list 1 & 2

However, the method containsAll() does not work in this use case, as 1234 does not occur in list1, and will result in a result of false, also contains() does not work.

Besides writing my own implementation(comparing all of the values individually from list2 to list1), is there a similar method to contains(), where a list of strings can be passed in, and compare that to another list, and return true if one or more values are contained in that list?

More Examples:

ArrayList list1 = {1, 2, 3, 4, 5}

ArrayList list2 = {1, 2, 3} --> True
ArrayList list2 = {3, 2, 1} --> True
ArrayList list2 = {5, 6, 7, 8, 9} --> True
ArrayList list2 = {6, 7, 8, 9} --> False
like image 388
DevelopingDeveloper Avatar asked Mar 16 '18 21:03

DevelopingDeveloper


People also ask

Does ArrayList contain duplicates?

ArrayList allows duplicate values in its collection. On other hand duplicate elements are not allowed in Hashset.

Can an ArrayList contain multiple references to the same object?

An ArrayList can contain multiple references to the same object. The same object may belong to 2 different ArrayLists. ArrayList's add method makes a copy of the object and adds it to the list. Two variables can refer to the same Arraylist.

How do you find duplicates in ArrayList?

One of the most common ways to find duplicates is by using the brute force method, which compares each element of the array to every other element. This solution has the time complexity of O(n^2) and only exists for academic purposes.

How do you check if an ArrayList contains another ArrayList?

ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.


3 Answers

Like list2.stream().anyMatch(list1::contains) in java 8.

like image 193
NiVeR Avatar answered Oct 05 '22 08:10

NiVeR


Pre-Java 8, you can use retainAll to achieve this quite simply:

Set<Foo> intersect = new HashSet<>(listOne);
intersect.retainAll(listTwo);
return !intersect.isEmpty();
like image 25
Michael Avatar answered Oct 05 '22 07:10

Michael


There's no need to use streams for this task. Use the Collections.disjoint method instead:

boolean result = !Collections.disjoint(list1, list2);

According to the docs:

Returns true if the two specified collections have no elements in common.

like image 45
fps Avatar answered Oct 05 '22 06:10

fps