英文:
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<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?
答案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<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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论