List集合根据对象某个属性去重
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Test { public static void main(String[] args) { List<User> list = new Lists.newArrayList(); list.add(new user(1,"张三","上海")); list.add(new user(2,"李四","北京")); list.add(new user(3,"王五","济南")); list.add(new user(4,"李四","北京")); // 根据list中的City城市来去重 newList = list.stream().filter(distinctByKey(User::getCity)).collect(Collectors.toList()); } 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; } }