1

I have this code

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

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?

merc-angel
  • 394
  • 1
  • 5
  • 13
  • 1
    I don't need to check other fields than currency. – merc-angel Oct 01 '20 at 15:38
  • "better" is subjective and opinion-based. Of course you can also grou the items by currency and then filter the map for non-singleton entries, then check if the result is empty. Thats more functional, but ultimately not more efficient. – Polygnome Oct 01 '20 at 15:42
  • Seems good to me – CryptoFool Oct 01 '20 at 15:42
  • 1
    Your way is absolutely fine. I guess you could use streams, but it would be more verbose and less expressive than your current approach – fps Oct 01 '20 at 15:42
  • Seems to me to be a duplicate of https://stackoverflow.com/questions/30053487/how-to-check-if-exists-any-duplicate-in-java-8-streams – Abra Oct 01 '20 at 15:43
  • not in this case in my opinion, because I check only certain value – merc-angel Oct 01 '20 at 15:44
  • 1
    The first answer contains basically the same code as in your question. – Abra Oct 01 '20 at 15:45
  • 1
    I think no, because I dont check whole object, but only field – merc-angel Oct 01 '20 at 15:46
  • 1
    @merc-angel It's the same, it doesn't matter whether you use the whole object or just an attribute – fps Oct 01 '20 at 15:53

1 Answers1

1

There are many ways to do that.

One simple and elegant way is the following.

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
}

Note that I changed the name to hasDuplicatesOfCurrency

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56