zoukankan      html  css  js  c++  java
  • java里面求交集并集补集


    import java.util.HashSet;
    import java.util.Set;
    
    public class test {
        public static void main(String[] args) {
            Set<Integer> result = new HashSet<Integer>();
            Set<Integer> set1 = new HashSet<Integer>(){{
                add(1);
                add(3);
                add(5);
            }};
    
            Set<Integer> set2 = new HashSet<Integer>(){{
                add(1);
                add(2);
                add(3);
            }};
    
            result.clear();
            result.addAll(set1); // 将集set1所有元素加到result集合
            result.retainAll(set2); // 仅保留result集合中那些包含在指定set2中的元素
            System.out.println("交集:"+result);
            
            result.clear();
            result.addAll(set1);
            result.removeAll(set2); // 移除result集合中那些包含在set2中的元素,有就删除,没有就继续删掉下一个元素
            System.out.println("差集:"+result);
    
            result.clear();
            result.addAll(set1);
            result.addAll(set2);
            System.out.println("并集:"+result);
    
        }
    }


    差集:一般地,记A,B是两个集合,则所有属于A且不属于B的元素构成的集合,叫做集合A减集合B(或集合A与集合B之差),类似地,对于集合A、B,我们把集合x∣x∈A,且x∉B叫做A与B的差集

    ========================================Talk is cheap, show me the code=======================================

    CSDN博客地址:https://blog.csdn.net/qq_34115899
  • 相关阅读:
    BMP图像信息隐藏
    多项式模2运算及求逆元
    day08 xml tomcat
    day07 c3p0连接池
    day06 多表查询
    java学习日记(day30--dbutils)
    java学习日记(29 JDBC)
    java学习日记(28)-- mysql基础
    activiti主要组件解析
    activiti流程跟踪图算法
  • 原文地址:https://www.cnblogs.com/lcy0515/p/9179794.html
Copyright © 2011-2022 走看看