Java List操作6(distinct—去重)
2019-08-08 本文已影响0人
雪飘千里
1、基本数据类型及String类型
- 1.JDK Set 去重
public static void main(String[] args)
{
List<String> list = new ArrayList();
list.add("123");list.add("123");
Set<String> set = new HashSet<>(list);
System.out.println(set);
}
- Java8 Stream
List<String> list = new ArrayList();
list.add("123");list.add("123");
List<String> ll = list.stream().distinct().collect(Collectors.toList());
2、List中对象去重
- 重写对象中hashCode方法和equals方法 去重
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
List<User> list = new ArrayList();
User user1 = new User();
user1.setId(1L); user1.setMobile("123456");
list.add(user1);
User user2 = new User();
user2.setId(1L); user2.setMobile("12345678");
list.add(user2);
// Set 去重
Set<User> set = new HashSet<>(list);
System.out.println(set);
//Java8 Stream
List<User> userList = list.stream().distinct().collect(Collectors.toList());
System.out.println(userList);
- Java8 Stream 去重
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;
//根据id去重
List<User> unique1 = list.stream().collect(
collectingAndThen(
toCollection(() -> new TreeSet<>(comparing(User::getId))), ArrayList::new));
System.out.println(unique1);
//根据id和mobile去重
List<User> unique2 = list.stream().collect(
collectingAndThen(
toCollection(() -> new TreeSet<>(comparing(o -> o.getId() + ";" + o.getMobile()))), ArrayList::new)
);
System.out.println(unique2);