Java判斷List中是否有重復元素


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("有重復元素");
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM