List: How to de-duplication according to an attribute of an object

List is de-duplicated according to an attribute of an object

public class Test {
    public static void main(String[] args) {
        List<User> list = new Lists.newArrayList();
        list.add(new user(1,"Zhang San", "ShangHai"));
        list.add(new user(2, "Li Si", "Beijing"));
        list.add(new user(3, "Wang Wu", "Jinan"));
        list.add(new user(4, "Li Si", "Beijing"));

        // de-duplicate the list according to the city in the list
        newList =;
    private static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;

Read More: