ArrayList contains one or more objects from another ArrayList

I have two ArrayLists (list1 and list2). I would like to see if in list 1 there are 1 (or more) objects in list2 (which are strings).

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 thisAll () method does not work in this use case, since it 1234does not appear in list1 and leads to the result false, it also contains () does not work.

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

Additional 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
+4
source share
4

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

+10

Pre-Java 8, keepAll :

Set<Foo> intersect = new HashSet<>(listOne);
intersect.retainAll(listTwo);
return !intersect.isEmpty();
+4

There is no need to use threads for this task. Use instead Collections.disjoint:

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

According to the docs:

Returns trueif the two specified collections do not have common elements.

+3
source
list2.removeAll(list1);

If you just need to return a boolean value. Use removeAll (), this will reduce the length of the list2, all elements (elements) will be deleted.

+1
source

Source: https://habr.com/ru/post/1694989/


All Articles