Java Collections disjoint()

disjoint() 检查两个指定的集合是否不相交。如果两个指定的集合没有相同的元素,则返回true。

1 语法

public static boolean disjoint(Collection<?> c1, Collection<?> c2)  

2 参数

c1:第一个集合。

c2:第二个集合。

3 返回值

如果两个指定的集合没有相同的元素,则返回true。

4 Collections disjoint()示例1

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.disjoint的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        //Create two lists
        List<String> list1 = new ArrayList<String>(5);
        List<String> list2 = new ArrayList<String>(10);
        //Add elements in both lists
        list1.add("Java");
        list1.add("PHP");
        list1.add("JavaScript");
        list2.add("C++");
        list2.add("C");
        list2.add("C#");
        //Check elements in both List
        //It returns true if no elements are common.
        boolean iscommon = Collections.disjoint(list1, list2 );
        System.out.println("Output: "+iscommon);
    }
}

输出结果为:

Output: false

5 Collections disjoint()示例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.disjoint的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        //Create two lists
        List<Integer> list = Arrays.asList(10, 20, 30, 40);
        List<Integer> list2 = Arrays.asList(10, 20, 30, 4, 5, 6);
        boolean b = Collections.disjoint(list, list2);
        System.out.println("Output: "+b);
    }
}

输出结果为:

Output: false

6 Collections disjoint()示例3

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.disjoint的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        //Create two lists
        List<String> list1 = new ArrayList<String>();
        list1.add("Facebook");
        list1.add("Instagram");
        list1.add("Twitter");
        List<String> list2 = new ArrayList<String>();
        list2.add("Whatsapp");
        list2.add("Hike");
        list2.add("Skype");
        //Check common elements in both lists
        boolean isCommon = Collections.disjoint(list1,list2);
        if(isCommon)
            System.out.println("Lists Must Have Nothing In Common!");
        else
            System.out.println("Lists Must Have Something In Common!");
        //Add one elements in the List1 and check for common elements again
        list1.add("Whatsapp");
        isCommon = Collections.disjoint(list1,list2);
        if(isCommon)
            System.out.println("Lists Must Have Nothing In Common!");
        else
            System.out.println("Lists Must Have Something In Common!");
    }
}

输出结果为:

Lists Must Have Nothing In Common!
Lists Must Have Something In Common!

 

热门文章

优秀文章