• 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("重复了,老铁");
    }
    
  • 相关阅读:
    JQuery EasyUI属性和常见用法
    iOS 设置随意屏幕旋转
    iOS 打印系统字体
    iOS 实时监测网络状态(通过Reachability)
    UITableView上添加按钮,按钮点击效果延迟的解决办法
    ios下通过webservice获取数据
    (转发)InputAccessoryView的使用方法
    (转发)IOS动画中的枚举UIViewAnimationOptions
    (转发)IOS高级开发~Runtime(四)
    (转发)IOS高级开发~Runtime(三)
  • 原文地址:https://www.cnblogs.com/netu/p/14818685.html
Copyright © 2020-2023  润新知