如何在对象列表中找到特定字段的重复项?

huangapple go评论74阅读模式
英文:

How to find duplicate of certain fields in List of objects?

问题

我有这段代码

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;
}

这段代码检查我是否在对象列表中具有重复的特定字段值。

我只需检查货币字段,无需检查其他字段。

是否有更好、更独特的方法来进行检查?

英文:

I have this code

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

This code check if I have duplicated values of certain fields in objects list.

I don't need to check other fields than currency.

Is there a better, more original way to check it?

答案1

得分: 1

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

其中一种简单而优雅的方法如下。

public static boolean hasDuplicatesOfCurrency(List<Account> inputList) {
    long distinctElements = inputList.stream()    // 使用流
        .map(account -> account.getCurrency())    // 考虑货币字段
        .distinct()                               // 仅考虑不同的值
        .count();                                 // 对它们计数
    return distinctElements != inputList.size();  // 将原始列表的大小与不同元素的数量进行比较
}

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

英文:

There are many ways to do that.

One simple and elegant way is the following.

public static boolean hasDuplicatesOfCurrency(List&lt;Account&gt; inputList) {
    long distinctElements = inputList.stream()    // Use a stream
        .map(account -&gt; 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
}

Note that I changed the name to hasDuplicatesOfCurrency

huangapple
  • 本文由 发表于 2020年10月1日 23:31:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/64158589.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定