demo
public class OTest {
static Map<Object, Boolean> seen = new ConcurrentHashMap<>(16);
public static void main(String[] args) {
List<SysUserRole> userRoleList = new ArrayList<>();
SysUserRole sysUserRole = new SysUserRole();
sysUserRole.setUserId("1");
sysUserRole.setRoleId(2L);
userRoleList.add(sysUserRole);
SysUserRole sysUserRole1 = new SysUserRole();
sysUserRole1.setUserId("1");
sysUserRole1.setRoleId(2L);
userRoleList.add(sysUserRole1);
// 函数去重
List<SysUserRole> a = userRoleList.stream().filter(distinctByKey(k -> k.getUserId() + ";" + k.getRoleId().toString())).collect(Collectors.toList());
System.out.println(JSON.toJSONString(a));
// 比较去重
userRoleList = userRoleList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getUserId() + ";" + o.getRoleId()))), ArrayList::new));
System.out.println(JSON.toJSONString(userRoleList));
}
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
}
标签:SysUserRole,sysUserRole1,java,sysUserRole,userRoleList,列表,static,new,属性
From: https://www.cnblogs.com/stubborn-dude/p/17622843.html