当前位置: 移动技术网 > IT编程>开发语言>Java > List集合多个复杂字段判断去重的案例

List集合多个复杂字段判断去重的案例

2019年07月19日  | 移动技术网IT编程  | 我要评论

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。如果你想了解更多相关内容请查看下面相关链接

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网