list去除相同String、对象元素

一、当相同元素为String时 方法一

    /**
     * List去重
     */
    private List<String> removeDuplicate(List<String> list) {
        LinkedHashSet<String> set = new LinkedHashSet<String>(list.size());
        set.addAll(list);
        list.clear();
        list.addAll(set);
        return list;
    }

方法二

        List<String> list= list.stream().distinct().collect(Collectors.toList());

二、当相同元素为对象时 方法一

    // 注意Comparator.comparing要根据参数的类型进行选择
    private List<GroupVO> removeDuplicateGroupVO(List<GroupVO> groupVOS){
        return groupVOS.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(
                                () -> new TreeSet<>(Comparator.comparing(GroupVO::getId))
                        ), ArrayList::new
                )
        );
    }

方法二

  public static List<Person> removeDupliById(List<Person> persons) {
        Set<Person> personSet = new TreeSet<>((o1, o2) -> o1.getId().compareTo(o2.getId()));
        personSet.addAll(persons);
 
        return new ArrayList<>(personSet);
    }

方法三

  public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> map = new ConcurrentHashMap<>();
        return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
 
  // remove duplicate
  persons.stream().filter(distinctByKey(p -> p.getId())).forEach(p -> System.out.println(p));

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×