List 通过对象属性过滤出想要的结果集 Java新特性

List 普通去重
List<User> list = Lists.newArrayList();
list.add(new User("1","180","18"));
list.add(new User("1","180","18"));
list.add(new User("2","170","18"));
list.add(new User("1","190","18"));
list.stream().distinct().collect(Collectors.toList());
System.out.println(list.size());
// 输出 3 ,去重后的结果集
List 按user属性进行过滤

通过Id过滤方式1

List<User> list = Lists.newArrayList();
list.add(new User("1","180","18"));
list.add(new User("1","180","18"));
list.add(new User("2","170","18"));
list.add(new User("1","190","18"));
Set<String> set = Sets.newHashSet();
list.stream().filter(p -> {
	if(set.contains(p.getId)){
		return false;
	} else {
		set.add(p.getId);
		return true;
	}
}).collect(Collectors.toList);
System.out.println(list.size());

通过id过滤方式2

List<User> list = Lists.newArrayList();
list.add(new User("1","180","18"));
list.add(new User("1","180","18"));
list.add(new User("2","170","18"));
list.add(new User("1","190","18"));
Set<String> set = Sets.newHashSet();
list.stream().collect(Collectors.collectionAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getId()))), ArrayList::new));
System.out.println(list.size());

你可能感兴趣的:(小小技术点)