Java List<T> 去重

1.List<T>,是个泛型,实际业务里,它经常是一个bean,例如Person类,里面有age、name等属性。

2.如果List<Person>  ps 有重复的数据,我们需要去重的话,就要在Person类里写上equal()方法和HashCode()方法。注:不写这个不能去重!

3.去重,我们就需要一个临时的List<Person> temp 集合来接收新数据,一个临时Person p 来接收循环的数据。

4.最后迭代去重。

List<Person> temp = new ArrayList()<>;

Person p = null;

List<Person> it = ps.iterator();

while (it.hasNext()) {

   p = it.next();

  if (!temp .contains(p)) {

    temp.add(p);

  }  

}

最后,temp 就是已去重的集合。

猜你喜欢

转载自www.cnblogs.com/hsz-csy/p/10241964.html