zoukankan      html  css  js  c++  java
  • JAVA中List数组判断是否有重复元数

    JAVA中List数组判断是否有重复元数

    1.使用Set的特性,将List转Set,比较两个集合的size()的大小是否相等
    List<String> strList=new ArrayList<>(Arrays.asList("张三","李四","李四","王五"));
    Set<String> strSet=new HashSet<>(strList);
    if (strList.size() == strSet.size()) {
        System.out.println("没有重复");
    } else {
        System.out.println("重复了,老铁");
    }
    
    2.使用jdk8---Stream的特性
    List<String> strList=new ArrayList<>(Arrays.asList("张三","李四","李四","王五"));
    long count = strList.stream().distinct().count();
    if (strList.size() == count) {
        System.out.println("没有重复");
    } else {
        System.out.println("重复了,老铁");
    }
    
    3.使用Object时判断成员变量是否有重复

    User类:

    @Data
    public class User {
        private Long id;
        private String name;
        private Integer age;
    
        public User(Long id, String name, Integer age) {
            this.id = id;
            this.name = name;
            this.age = age;
        }
    
        public User() {
        }
    }
    

    判断User集合中name是否有重复:

    List<User> users = new ArrayList<User>(){
        {
            add(new User(13131l,"张三",33));
            add(new User(21244l,"李四",23));
            add(new User(31865l,"王五",41));
            add(new User(31231l,"大聪明",25));
            add(new User(31123l,"大智慧",27));
            add(new User(38751l,"张三",30));
        }
    };
    List<String> names = users.stream().map(User::getName).collect(Collectors.toList());
    System.out.println(names.toString());
    //distinct()过滤重复的姓名 count()计算数量
    long count = names.stream().distinct().count();
    System.out.println("去重后的个数:"+count);
    if (names.size() == count){
        System.out.println("没有重复");
    }else {
        System.out.println("重复了,老铁");
    }
    
  • 相关阅读:
    powershell命令大全
    Android USB Connections Explained: MTP, PTP, and USB Mass Storage
    安装Windows Metasploit Framework
    Sublime Text2 jedi插件离线安装
    MySQL下载安装配置和Navicat for MySQL的安装配置
    Sublime中文编码问题
    Flask入门之结构重组(瘦身)-第13讲笔记
    Flask入门之SQLAlchemy配置与数据库连接
    Flask入门之flask-wtf表单处理
    Total Command使用笔记
  • 原文地址:https://www.cnblogs.com/netu/p/14818685.html
Copyright © 2011-2022 走看看