在业务中,经常会遇到需要根据对象中的某个字段进行去重,以下是比较方便的两个方法:
public class StreamUtil {
/**
* 流式去重工具
*
* @param function
* @param <K>
* @return
*/
public static <K> Predicate<K> distinctPredicate(Function<K,Object> function){
Map<Object, Boolean> map = new ConcurrentHashMap<>();
return (t)-> null == map.putIfAbsent(function.apply(t),true);
}
/**
* 将集合先放到 treeSet 集合然后将他们转换成数组,根据集合内对象的某个属性去重
* 将o -> o.hashCode()换成对应的属性即可
*
* @param list
* @return
*/
public static List<Object> distinctByTreeSet(List<Object> list){
List<Object> distinctList = list.stream().collect(
// 将集合先放到 treeSet 集合然后将他们转换成数组
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.hashCode())))
, ArrayList::new)
);
return distinctList;
}
public static void main(String[] args) {
User user1 = new User(1, "小明");
User user2 = new User(2, "小明");
List<User> users = new ArrayList<>();
users.add(user1);
users.add(user2);
List<User> distinctUserList= users.stream().filter(distinctPredicate(m -> m.getName())).collect(Collectors.toList());
System.out.println(distinctUserList);
}
@Data
@AllArgsConstructor
@NoArgsConstructor
static class User{
private Integer id;
private String name;
}
}