Java set operations -- intersection and union of two sets

Source: Internet
Author: User

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 !!!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.