[英]Collection Utils removing duplicates object
我有一個對象Person(id,name)。
public class Person {
/** Personid. **/
private Long personId;
/** Person Adresse. **/
private String adresse
// Getters, Setters
如何使用CollectionUtils刪除重復的人(具有相同的ID)? 例如Person1(10,aaaa),Person2(10,bbbb),Person3(20,cccc)結果=> Person1(10,aaaa),Person3(30,cccc)
編輯:
此解決方案使用Set並覆蓋等於和哈希碼進行工作:
List<Person> oldPerson = new ArrayList<>();
//oldPerson.add ...
Set<Person> newPerson = new HashSet<>(oldPerson);
List<Person> theRightPerson = new ArrayList<>(newPerson);
我正在尋找的解決方案是這樣的:
List<Person> theRightPerson = (List<Person>) CollectionUtils.collect(oldPerson, new Transformer() {
@Override
public Object transform(Object input) {
// TODO Auto-generated method stub
return null;
}
})
覆蓋equals和hashcode方法以及使用HashSet會更容易實現。 如果您無法編輯類的源代碼,則需要遍歷列表並根據條件比較每個項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.