List去重復,我們首先想到的可能是 利用List
轉Set
集合,因為Set
集合不允許重復。所以達到這個目的。 如果集合里面是簡單對象,例如Integer
、String
等等,這種可以使用這樣的方式去重復。但是如果是復雜對象,即我們自己封裝的對象。用List轉Set 卻達不到去重復的目的。 所以,回歸根本。 判斷Object
對象是否一樣,我們用的是其equals
方法。 所以我們只需要重寫equals
方法,就可以達到判斷對象是否重復的目的。
話不多說,上代碼:
package com.test;import java.math.BigDecimal;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import org.apache.commons.collections.CollectionUtils;public class TestCollection { //去重復之前集合 private static List<User> list = Arrays.asList( new User("張三", BigDecimal.valueOf(35.6), 18), new User("李四", BigDecimal.valueOf(85), 30), new User("趙六", BigDecimal.valueOf(66.55), 25), new User("趙六", BigDecimal.valueOf(66.55), 25), new User("張三", BigDecimal.valueOf(35.6), 18)); public static void main(String[] args) { //排除重復 getNoRepeatList(list); } /** * 去除List內復雜字段重復對象 * @param oldList * @return */ private static List<User> getNoRepeatList(List<User> oldList){ List<User> list = new ArrayList<>(); if(CollectionUtils.isNotEmpty(oldList)){ for (User user : oldList) { //list去重復,內部重寫equals if(!list.contains(user)){ list.add(user); } } } //輸出新集合 System.out.println("去除重復后新集合:"); if(CollectionUtils.isNotEmpty(list)){ for (User user : list) { System.out.println(user.toString()); } } return list; } static class User{ private String userName; //姓名 private BigDecimal score;//分數(shù) private Integer age; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public BigDecimal getScore() { return score; } public void setScore(BigDecimal score) { this.score = score; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public User(String userName, BigDecimal score, Integer age) { super(); this.userName = userName; this.score = score; this.age = age; } public User() { // TODO Auto-generated constructor stub } @Override public String toString() { // TODO Auto-generated method stub return "姓名:"+ this.userName + ",年齡:" + this.age + ",分數(shù):" + this.score; } /** * 重寫equals,用于比較對象屬性是否包含 */ public boolean equals(Object obj) { if (obj == null) { return false; } if (this == obj) { return true; } User user = (User) obj; //多重邏輯處理,去除年齡、姓名相同的記錄 if (this.getAge() .compareTo(user.getAge())==0 && this.getUserName().equals(user.getUserName()) && this.getScore().compareTo(user.getScore())==0) { return true; } return false; } }}
執(zhí)行結果:
去除重復后新集合:
姓名:張三,年齡:18,分數(shù):35.6
姓名:李四,年齡:30,分數(shù):85
姓名:趙六,年齡:25,分數(shù):66.55
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VeVb武林網的支持。
新聞熱點
疑難解答
圖片精選