1.如果是List<String>,List<Long>这种,可直接使用JDK1.8新特性stream的distinct方法
List<String> list = Arrays.asList("a", "b", "c", "a","a", "b");
List<String> newList = list.stream().distinct().collect(Collectors.toList());
newList.forEach(System.out::println);
2.如果List中是User这种对象,则需要重写User的equals和hashCode方法,然后放入Set集合来做去重
package com.example.springboot.demo.model;
import lombok.Data;
import lombok.ToString;
import java.math.BigDecimal;
import java.util.Objects;
@Data
@ToString
public class User {
private Long id;
private String name;
private String phone;
public User(Long id, String name,String phone) {
this.id = id;
this.name = name;
this.phone = phone;
}
@Override
public boolean equals(Object o) {
User user = (User) o;
return Objects.equals(name, user.name) &&
Objects.equals(phone, user.phone);
}
@Override
public int hashCode() {
return Objects.hash(name, phone);
}
}
这里equals方法是通过比较name和phone两个属性,来确定是不是同一个对象。
测试结果:
public static void main(String[] args) {
List<User> userList = new ArrayList<>();
userList.add(new User(18L, "peter","13222222222"));
userList.add(new User(19L, "peter","13222222222"));
userList.add(new User(13L, "peter","13777777777"));
userList.add(new User(16L, "jack","13222222222"));
userList.add(new User(22L, "tom","13333333333"));
userList.add(new User(32L, "tom","13333333333"));
Set<User> userSet = new HashSet<>(userList);
userSet.forEach(System.out::println);
}