List list = UserMapper.selectByIds(List ids); //根据某个字段进行去重
List users= list.stream() .filter(distinctByKey(User::getName)) .collect(Collectors.toList());
private static Predicate distinctByKey(Function keyExtractor) { Map<Object, Boolean> seen = new ConcurrentHashMap<>(); return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; }
注:putIfAbsent() 方法会先判断指定的键(key)是否存在,不存在则将键/值对插入到 HashMap 中。