Set collection: find intersection, union and difference

package com.miaoqiang.collectiontest;

import java.util.*;

/**
 * 求set集合的交集、并集和差集
 * @Author: 苗晓强
 * @Date: 2021/11/29 17:31
 */
public class SetTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入A集合大小,系统会自动生成相对应数量的元素的集合:");
        int i = scanner.nextInt();
        Set<Integer> setA = new HashSet<Integer>();
        for (int j = 0; j < i; j++) {
            setA.add(getRandomNumbers());
        }
        System.out.println("迭代器展示集合A的内容:");
        Iterator<Integer> iterator = setA.iterator();
        while (iterator.hasNext()){
            System.out.print(iterator.next() + " ");
        }
        System.out.println();
        System.out.println("for循环展示集合A的内容:");
        for (Integer number: setA) {
            System.out.print(number + " ");
        }
        System.out.println();
        System.out.println("请输入B集合大小,系统会自动生成相对应数量的元素的集合:");
        int m = scanner.nextInt();
        Set<Integer> setB = new HashSet<Integer>();
        for (int j = 0; j < m; j++) {
            setB.add(getRandomNumbers());
        }
        System.out.println(setB.size());
        System.out.println("迭代器展示集合B的内容:");
        Iterator<Integer> iterator1 = setB.iterator();
        while (iterator1.hasNext()){
            System.out.print(iterator1.next() + " ");
        }
        System.out.println();
        Set<Integer> result = new HashSet<Integer>();
        //添加集合A的数据到result中
        result.addAll(setA);
        //求集合A和集合B的交集
        //result.retainAll(setB);
        //System.out.println("集合A和B的交集是:" + result);
        //求两个集合的并集  因为set无序不重复的特性,决定了,求并集,直接添加即可
        //result.addAll(setB);
        //System.out.println("集合A和B的并集是:" + result);

        result.addAll(setA);
        result.removeAll(setB);
        System.out.println("集合A和集合B的差集:" + result);

    }

    /**
     * 随机获取 1~100的数字
     * @return
     */
    private static Integer getRandomNumbers() {
        Random random = new Random();
        return random.nextInt(100) + 1;
    }
}

Reflection: It mainly uses the non-repetitive feature of the Set collection, and the main methods involved are 

result.addAll(setA);
result.retainAll(setB);
result.removeAll(setB);

At the same time, the Scanner class is used to read data from the console, the random class Random generates numbers randomly, and the Iterator iterator is used to loop through the Set collection. The disadvantage is that when setting the collection capacity of the collection B, sporadic Decrease the capacity of the set by one, that is, the input in the console is 6, but the capacity of set B is 5, and I haven't figured it out yet.

Guess you like

Origin blog.csdn.net/mnimxq/article/details/121621156