使用Stream对List对象去重
本文章主要对集合中的重复数据进行去重。
public class Distinct {
public static void main(String[] args) {
User user1 = new User();
User user2 = new User();
User user3 = new User();
user1.setId(1);
user2.setId(2);
user3.setId(3);
user1.setName("李1");
user2.setName("李1");
user3.setName("李3");
List<User> userList = List.of(user1, user2, user3);
//java11
List<String> repeatList = List.of("我", "我", "是", "是", "李", "二", "李", "二", "狗", "狗");
userList.forEach(
i -> System.out.print(i.getId() + "-" + i.getName() + " ")
);
repeatList.forEach(
System.out::print
);
System.out.println("\n================去重后================");
//filter()里面只要返回boolean,逻辑可以自己写
repeatList = repeatList.stream().distinct().collect(Collectors.toList());
Set<String> userName = new HashSet<>();
userList = userList.stream().filter(
i -> {
if (!userName.contains(i.name)) {
userName.add(i.name);
return true;
}
return false;
}
).collect(Collectors.toList());
userList.forEach(
i -> System.out.print(i.getId() + "-" + i.getName() + " ")
);
repeatList.forEach(
System.out::print
);
}
static class User {
Integer id;
String name;
//GET、SET
}
}