首页 > 编程语言 > 详细

【java】集合操作中的retainAll的坑

时间:2021-06-08 13:37:37      阅读:18      评论:0      收藏:0      [点我收藏+]

 

JDK1.8

首先,set1中有值, set2中无值

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Sets;
import java.util.*;



public class ListTest {

    public static void main(String[] args) throws Exception {

        Set<Long> set1 = new HashSet<>();
        set1.add(1L);
        set1.add(2L);

        Set<Long> set2 = new HashSet<>();


        Sets.SetView<Long> intersection = Sets.intersection(set1, set2);
        System.out.println(JSON.toJSONString(intersection));

        System.out.println(JSON.toJSONString(set1));
        System.out.println(JSON.toJSONString(set2));


        set1.retainAll(set2);
        System.out.println(JSON.toJSONString(set1));
        System.out.println(JSON.toJSONString(set2));

    }
}

结果:

技术分享图片

 

 

 

 

再来一次,set2中放值

public static void main(String[] args) throws Exception {

        Set<Long> set1 = new HashSet<>();
        set1.add(1L);
        set1.add(2L);

        Set<Long> set2 = new HashSet<>();
        set2.add(1L);

        Sets.SetView<Long> intersection = Sets.intersection(set1, set2);
        System.out.println(JSON.toJSONString(intersection));

        System.out.println(JSON.toJSONString(set1));
        System.out.println(JSON.toJSONString(set2));


        set1.retainAll(set2);
        System.out.println(JSON.toJSONString(set1));
        System.out.println(JSON.toJSONString(set2));

    }

结果如下

技术分享图片

 

【java】集合操作中的retainAll的坑

原文:https://www.cnblogs.com/sxdcgaq8080/p/14861965.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!