首页 > 编程语言 > 详细

Java判断List中是否有重复元素

时间:2020-06-19 17:23:00      阅读:59      评论:0      收藏:0      [点我收藏+]

Java判断List中是否有重复元素

1.将List转为Set,通过2个集合的size大小是否相等来判断有无重复元素

public static void main(String[] args) {
    List<String> stringList=new ArrayList<>(Arrays.asList("a","a","b","c"));
    Set<String> stringSet=new HashSet<>(stringList);
    if (stringList.size() == stringSet.size()) {
        System.out.println("没有重复元素");
    } else {
        System.out.println("有重复元素");
    }
}

2.使用jdk8的Stream来判断

public static void main(String[] args) {
    List<String> stringList=new ArrayList<>(Arrays.asList("a","a","b","c"));
    long count = stringList.stream().distinct().count();
    if (stringList.size() == count) {
    System.out.println("没有重复元素");
    } else {
    System.out.println("有重复元素");
    }
}

3.实际开发场景中

实际使用中,需要判断重复的元素可能在对象集合中每个对象的某个成员变量中,可以用jdk8的Stream很方便的获得想要的成员变量的集合,再判断是否有重复元素。

新建一个Person类:

public class Person {
    private String name;
    
    public Person(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

判断Person集合中的name属性有没有重复

public static void main(String[] args) {
    List<Person> personList = new ArrayList<Person>(){{
        add(new Person("张三"));
        add(new Person("李四"));
        add(new Person("张三"));
    }};
    List<String> stringList = personList.stream().map(Person::getName)
        .collect(Collectors.toList());
    long count = stringList.stream().distinct().count();
    if (stringList.size() == count) {
        System.out.println("没有重复元素");
    } else {
        System.out.println("有重复元素");
    }
}

Java判断List中是否有重复元素

原文:https://www.cnblogs.com/debugginging/p/13163813.html

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