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
ArrayList allows duplicate values in its collection. On other hand duplicate elements are not allowed in Hashset.
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.
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.
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.
Like list2.stream().anyMatch(list1::contains)
in java 8.
Pre-Java 8, you can use retainAll to achieve this quite simply:
Set<Foo> intersect = new HashSet<>(listOne);
intersect.retainAll(listTwo);
return !intersect.isEmpty();
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.
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