【问题标题】:How to find duplicate of certain fields in List of objects? [closed]如何在对象列表中查找某些字段的重复项? [关闭]
【发布时间】:2020-10-01 23:54:38
【问题描述】:

我有这个代码

public static boolean haveDuplicatesOfCurrency(List<Account> inputList){
Set<String> currencyCode = new HashSet<>();
for (Account account: inputList) {
    boolean add = currencyCode.add(account.getCurrency());
    if(!add){
        return true;
    }
}
return false;
}

此代码检查对象列表中某些字段的值是否重复。

我不需要检查货币以外的其他字段。

有没有更好、更新颖的检查方式?

【问题讨论】:

  • 我不需要检查货币以外的其他字段。
  • 你的方式绝对没问题。我想您可以使用流,但它会比您当前的方法更冗长且缺乏表现力
  • 第一个答案包含与您的问题基本相同的代码。
  • 我认为没有,因为我不检查整个对象,而只检查字段
  • @merc-angel 一样,用整个对象还是只用一个属性都没关系

标签: java


【解决方案1】:

有很多方法可以做到这一点。

一种简单而优雅的方式如下。

public static boolean hasDuplicatesOfCurrency(List<Account> inputList) {
    long distinctElements = inputList.stream()    // Use a stream
        .map(account -> account.getCurrency())    // Consider the currency field
        .distinct()                               // Consider only distinct values
        .count();                                 // count them
    return distinctElements != inputList.size();  // Check the size of the original list with the number of distinct elements
}

请注意,我将名称更改为 hasDuplicatesOfCurrency

【讨论】:

    猜你喜欢
    • 2021-08-26
    • 2022-01-07
    • 1970-01-01
    • 2017-08-31
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 2015-03-11
    相关资源
    最近更新 更多