1. Use the retainAll method
retainAll
yesCollection
A method in the interface that preserves the same elements in the set as the specified set and removes other elements.
principle:
-
retainAll
The method will iterate over the current collection and check whether each element exists in the specified collection. - If the element does not exist in the specified collection, the element is removed from the current collection.
- Ultimately, the current collection only retains the same elements as the specified collection.
retainAll
It's in JavaList
An method provided by the interface is used to retain the same elements in the list as in the specified collection and remove all other elements. in other words,retainAll
The method will modify the current list so that it only contains the same elements as in the specified collection.
Method definition
boolean retainAll(Collection<?> c);
parameter:
-
c
: Contains a collection that needs to be preserved.
Return value:
- If the list changes due to calling this method, return
true
。 - If the list has not changed (i.e. the list already contains only elements in the specified collection), then return
false
。
Method behavior
-
Keep intersection:
retainAll
The method retains the intersection of the current list and the specified set. - Remove other elements: Elements in the current list that are not in the specified collection will be removed.
-
Modify the original list:
retainAll
The method will directly modify the current list, rather than returning a new list.
Sample code
Here is a simple example showingretainAll
Method usage:
import ; import ; public class RetainAllExample { public static void main(String[] args) { // Create two lists List<String> list1 = new ArrayList<>(); ("Apple"); ("Banana"); ("Cherry"); ("Date"); List<String> list2 = new ArrayList<>(); ("Banana"); ("Date"); ("Fig"); // Call the retainAll method boolean isChanged = (list2); // Output result ("Did List1 change: " + isChanged); // true ("List1's content: " + list1); // [Banana, Date] ("List2's content: " + list2); // [Banana, Date, Fig] } }
Output:
List1 Have there been any changes: true List1 Contents: [Banana, Date] List2 Contents: [Banana, Date, Fig]
Key points
-
Modify the original list:
-
retainAll
The method will directly modify the list that calls it, rather than returning a new list. - If you need to keep the original list, you can call it
retainAll
Create a copy before.
-
-
Return value:
- If the list is called
retainAll
If a change occurs, returntrue
。 - If the list has not changed (i.e. the list already contains only elements in the specified collection), then return
false
。
- If the list is called
-
Collection comparison:
-
retainAll
Methods depend onequals
Method to compare whether the elements are the same. - If the collection contains custom objects, make sure it has been rewrited correctly.
equals
andhashCode
method.
-
-
Empty collection:
- If the incoming collection is empty (
null
or empty set),retainAll
Will be thrownNullPointerException
Or clear the current list.
- If the incoming collection is empty (
Things to note
-
Performance issues:
-
retainAll
The time complexity of the method depends on the implementation of the list. ForArrayList
, the time complexity is O(n*m), where n is the size of the list and m is the size of the set. - If both lists and collections are large, performance may be affected.
-
-
Collection Type:
-
retainAll
The method can accept any implementationCollection
The object of the interface is used as a parameter, for exampleList
、Set
wait.
-
-
Repeat elements:
- If there are duplicate elements in the list and there are no duplicate elements in the specified collection,
retainAll
Repeated elements in the list will be retained. - For example:
- If there are duplicate elements in the list and there are no duplicate elements in the specified collection,
List<String> list1 = new ArrayList<>(("A", "A", "B", "C")); List<String> list2 = new ArrayList<>(("A", "B")); (list2); (list1); // Output [A, A, B]
Note:
-
retainAll
Methods are used to retain the same elements in the list as in the specified collection and remove other elements. - It directly modifies the original list and returns a boolean value indicating whether the list has changed.
- When using it, you need to pay attention to performance issues and compatibility of collection types.
- If you need to keep the original list, you can call it
retainAll
Create a copy before.
2. Use the Stream API
Java 8 has introducedStream
API, which can easily operate on collections.
principle:
- use
stream()
The method willList
Convert to stream. - use
filter
Method filters out elements that exist in another collection. - use
collect
Method collects the results into a newList
middle.
Sample code:
import ; import ; import ; public class Main { public static void main(String[] args) { List<Integer> list1 = new ArrayList<>(); (1); (2); (3); List<Integer> list2 = new ArrayList<>(); (2); (3); (4); List<Integer> intersection = () .filter(list2::contains) .collect(()); (intersection); // Output: [2, 3] } }
3. Manual traversal
Manually traverse twoList
and find common elements.
principle:
- Traversing the first one
List
Each element in it. - Check if this element exists in the second
List
middle. - If present, add it to the result set.
Sample code:
import ; import ; public class Main { public static void main(String[] args) { List<Integer> list1 = new ArrayList<>(); (1); (2); (3); List<Integer> list2 = new ArrayList<>(); (2); (3); (4); List<Integer> intersection = new ArrayList<>(); for (Integer item : list1) { if ((item)) { (item); } } (intersection); // Output: [2, 3] } }
Summarize
-
retainAll
The method is the most direct way, but it will modify the original collection. -
Stream
The API provides a more flexible and functional programming method without modifying the original collection. - Manual traversal is suitable for scenarios where custom logic is required, but the amount of code is large.
Just choose the appropriate method according to the specific needs.
This is the article about Java's multiple implementations of intersection elements of two List collections. For more related contents of two List collections, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!