Java Collection class list Intersection

Source: Internet
Author: User

The mathematical definition of the set intersection is as follows:

AAndBIntersection writing"ABytesB". Form:

XBelongABytesBWhen and only when

  • XBelongA, And
  • XBelongB.

The Java Collection class list also provides a built-in method to calculate the intersection of the two list sets.

The method is as follows:

public boolean retainAll(Collection<?> c)

Subclass must implement this method.

The following code uses the subclass arraylist as an example:

 

View Source

 

Print?

01 public class ListDemo {
02  
03     /**
04      * @param args
05      */
06     public static void main(String[] args) {
07     List<String> sList = new ArrayList<String>();
08     List<String> sList2 = new ArrayList<String>();
09     sList.add("1");
10     sList.add("2");
11     sList.add("3");
12     sList.add("4");
13      
14     sList2.add("1");
15     sList2.add("3");
16     sList2.add("5");
17      
18     sList.retainAll(sList2);
19      
20     for(String s : sList){
21         System.out.println(s);
22     }
23     }
24  
25 }

Output: 1
3

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.