List 去重两种方式:stream(需要JDK1.8及以上)、HashSet

1、使用Stream 方法 使用JDK1.8及以上
复制代码
  /**
     * Java合并两个List并去掉重复项的几种做法
     * @param args
     */
    public static void main(String[] args) {

        String[] str1 = {"1", "2", "3", "4", "5", "6"};
        List<String> list1 = new ArrayList<>(Arrays.asList(str1));

        String[] str2 = {"4", "5", "8", "10", "3"};
        List<String> list2= new ArrayList<>(Arrays.asList(str2));
        // 去重信息
        List<String> collect= Stream.of(list1,list2)
                .flatMap(Collection::stream)
                .distinct()
                .collect(Collectors.toList());
        for (String str:collect) {
           log.info("测试结果:"+str);
        }
}

运行结果如下:

2、HashSet集合的方式进行去重

复制代码
      /**
     * Java合并两个List并去掉重复项的几种做法
     * @param args
     */
    public static void main(String[] args) {
        String[] str1 = {"1", "2", "3", "4", "5", "6"};
        List<String> list1 = new ArrayList<>(Arrays.asList(str1));

        String[] str2 = {"4", "5", "8", "10", "3"};
       log.info("=====================HashSet去重操作======================");
        Set<String> set = new HashSet<>(list1);
        set.addAll(list2);
        List<String> list = new ArrayList<>(set);
        log.info("hashSet去重:"+list);
   }

运行结果如下:

相关推荐
wardenlzr18 分钟前
VSCode 运行 Live Server 提示「Windows 找不到文件 Chrome」问题全解析
chrome·windows·vscode
好好沉淀2 小时前
Windows 下升级 Maven 3.6.1 到 3.9.9 踩坑全记录
java·windows·maven
weixin_436525072 小时前
Windows 上终止占用的端口进程
windows
古道青阳2 小时前
Duilib 技术全景剖析
c++·windows
jing.wang_20253 小时前
NVIDIA CUDA C++编程环境搭建--Windows + Ubuntu 22.04
c++·windows·ubuntu·gpu算力
wechatbot8884 小时前
解决企业微信官方 API 短板:iPad 协议全功能对接方案
java·汇编·windows·http·微信·企业微信
测试专家4 小时前
PCI-1553B板卡在 Windows Server 2016 服务器安装流程详解
服务器·windows·单片机
西邮彭于晏4 小时前
Conda 常用命令速查手册:从入门到精通
windows·conda
米尔的可达鸭4 小时前
UDP 通信深度实验:从 Windows FastPath 到 ICMP 端口不可达的完整排查
windows·websocket·网络协议·rust·udp·wireshark·tcpdump
WangWei_CM5 小时前
Windows 进程枚举的 Native API 缓冲区遍历
windows