java8中List根据某一字段去重
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {
private String userid;
private String username;
private String age;
private String address;
}
package test;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class Test1 {
public static void main(String[] args) {
List<User> userList = new ArrayList<>();
userList.add(new User("1","李大锤","23","南京"));
userList.add(new User("2","张无忌","18","西安"));
userList.add(new User("3","刘德华","26","苏州"));
userList.add(new User("4","郭靖","33","上海"));
userList.add(new User("1","李大锤","23","南京")); //id相同,其他数据也相同
userList.add(new User("3","带头大哥","36","杭州")); //id相同,其他数据不同
System.out.println(userList);
//根据userid去重
userList = userList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User :: getUserid))), ArrayList::new));
System.out.println(userList);
}
}
可以看出,此操作把后面的两个id相同的都给剔除了。若两个id一样,其他数据不同的话,留下的数据是靠前的数据,剔除的是靠后的数据。