【Java】【48】List去重

前言:

1,for循环去重

2,hashSet去重

3,Stream去重

正文:

//取ID不重复的数据
public class User {
  private Integer id;
  private String name;
}


List<User> users = Lists.newArrayList(
        new User(1, "a"),
        new User(1, "b"),
        new User(2, "b"),
        new User(1, "a"));

1,for循环去重

public void dis1() {
    List<User> result = new LinkedList<>();
    for (User user : users) {
      boolean b = result.stream().anyMatch(u -> u.getId().equals(user.getId()));
      if (!b) {
        result.add(user);
      }
    }

    System.out.println(result);
}

2,hashSet去重

public void dis2() {
    Set<User> result = new HashSet<>(users);
    System.out.println(result);
}

重写hashcode和equals方法

//user类中
@Override
public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    User user = (User) o;
    return Objects.equals(id, user.id);
}

@Override
public int hashCode() {
    return Objects.hash(id);
}

//Objects.hash()这个方法的源码中
//result = 31 * result + (element == null ? 0 : element.hashCode());

3,Stream去重

public void dis3() {
    users.parallelStream().filter(distinctByKey(User::getId))
        .forEach(System.out::println);
}


public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Set<Object> seen = ConcurrentHashMap.newKeySet();
    return t -> seen.add(keyExtractor.apply(t));
}

Stream有distinct方法,但是没有提供自定义条件,要自定义条件,需要重写hashcode和equals方法,否则可以直接使用

users.parallelStream().distinct().forEach(System.out::println);

参考博客:

Java中对List去重, Stream去重 - Ryan.Miao - 博客园
https://www.cnblogs.com/woshimrf/p/java-list-distinct.html

HashSet的去重问题 - qq_28385797的博客 - CSDN博客
https://blog.csdn.net/qq_28385797/article/details/72834970

如何正确的重写equals() 和 hashCode()方法 - Zone - CSDN博客
https://blog.csdn.net/zzg1229059735/article/details/51498310

猜你喜欢

转载自www.cnblogs.com/huashengweilong/p/11374518.html
今日推荐