List集合多個複雜字段判斷去重的案例

今天小編就爲大家分享一篇關於List集合多個複雜字段判斷去重的案例,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧

List去重複,我們首先想到的可能是 利用ListSet集合,因爲Set集合不允許重複。所以達到這個目的。 如果集合裏面是簡單對象,例如IntegerString等等,這種可以使用這樣的方式去重複。但是如果是複雜對象,即我們自己封裝的對象。用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;//分數
 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 + ",分數:" + 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; 
   } 
 }
}

執行結果:

去除重複後新集合:
姓名:張三,年齡:18,分數:35.6
姓名:李四,年齡:30,分數:85
姓名:趙六,年齡:25,分數:66.55

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對神馬文庫的支持。如果你想了解更多相關內容請查看下面相關鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章