In Python, perhaps we don't have this annoyance, because Python has provided us with a way to intersection.
But in Java, we need to move our brains. The Collectionutils tool class of Apache is highly recommended here.
The method signature is as follows:
org.apache.commons.collections.intersection (Final Collection A, final Collection b)
So how does this approach come true? Here's an example of list
Public class Testintersection {
private static final Integer one = new in Teger (1);
-
-
Public static void main (string[] args) {
-
//A set [A,a,b,b,b,c]
-
list<string> a = arrays.aslist ( "a" ,&NBSP; "a" ,&NBSP; "B" Span style= "Color:black" >,&NBSP; "B" , "B" ,&NBSP; "C"
-
//b Set [A,b,b,c,c]
-
List<string> B = arrays.aslist ("A", "B" , "B", "C" , "C");
-
Map Mapa = Mapforcollection (a);
-
Map MAPB = mapforcollection (b);
-
//Add the elements that are not duplicated in the two collection, and then loop through the occurrences of the element in turn
-
Set set = new HashSet (a);
-
Set.addall (b);
-
list<string> result = new arraylist<string> ();
-
for (Object obj:set) {
-
for (int i = 0, m = math.min (Getcountsfrommap (obj, Mapa), Getcountsfrommap (obj, MAPB)); I < m; i++) {
-
Result.add ((String) obj);
-
}
-
}
-
//Look at the expected result is not [a,b,b,c]
-
SYSTEM.OUT.PRINTLN (result);
-
-
}
-
-
/**
-
* Loop through the collection and count the number of occurrences of each element <br/>
-
* Eventually return a map similar to {a:1,b:3,c:3}
-
*
-
* @param a
-
* @return
-
*/
-
Private static Map mapforcollection (Collection a) {
-
Map map = new HashMap ();
-
Iterator it = A.iterator ();
-
while (It.hasnext ()) {
-
Object obj = It.next ();
-
Integer count = (integer) map.get (obj);
-
if (count = = null) {
-
//indicates that the element first appears
-
Map.put (obj, one);
-
} Else {
-
Map.put (obj, new Integer (count.intvalue () + 1));
-
}
-
}
-
return map;
-
}
-
-
Private static int getcountsfrommap (Object obj, map map) {
-
Integer count = (integer) map.get (obj);
-
return count! = NULL ? Count.intvalue (): 0 ;
-
}
-
}
As you can see, the elements are marked on two different sets, the number of occurrences of each element is noted, and the elements that are not duplicated in the two collection are extracted.
Take the least number of elements in both, and loop to add
How to find the intersection of two sets in Java