Java calculates the intersection and union of two sets
How does Java calculate the intersection and union of two sets ?? In fact, Java APIs have encapsulated methods. Today, I will write a simple example to test it: (Java. util. Collections list is used as an example)
Calculate the intersection of connected sets:
Import Java. util. arraylist; import Java. util. list; public class testcollection {public static void main (string [] ARGs) {list <string> strlist = new arraylist <string> (); list <string> strlist2 = new arraylist <string> (); For (INT I = 0; I <10; I ++) {strlist. add ("AAA>" + I); strlist2.add ("AAA>" + (10-I);} // obtain the intersection strlist2.retainall (strlist); system. out. println ("intersection size:" + strlist2.size (); For (INT I = 0; I <strlist2.size (); I ++) {system. out. println (strlist2.get (I ));}}}
Calculate the union of the two sets:
Import Java. util. arraylist; import Java. util. list; public class testcollection {public static void main (string [] ARGs) {list <string> strlist = new arraylist <string> (); list <string> strlist2 = new arraylist <string> (); For (INT I = 0; I <10; I ++) {strlist. add ("AAA>" + I); strlist2.add ("AAA>" + (10-I);} // obtain the Union strlist2.removeall (strlist ); strlist2.addall (strlist); system. out. println ("Union set size:" + strlist2.size (); For (INT I = 0; I <strlist2.size (); I ++) {system. out. println (strlist2.get (I ));}}}
The example is very simple and I hope it will help you !!!