Java list 根据对象属性去重

上次写过stream流的博文中有用到Java8 list对象属性去重

Posted by Rong on February 26, 2019
  • 直接上码:

            // 根据scId去重
    ArrayList<Quota> collect = tickets.stream().collect(
                    Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparingLong(Quota::getScId))), ArrayList::new));
              
    

    我写这段代码的时候自己先模拟出数据结构,重写了对象的equals和hashCode方法,但是不够简洁,参考stackoverflow上大神的,写出以上代码。

  • 回顾下stackoverflow的,参考资料

    You can get a stream from the List and put in in the TreeSet from which you provide a custom comparator that compares id uniquely.
      
    Then if you really need a list you can put then back this collection into an ArrayList.
      
    下面的代码就不复制过来了,具体根据参考资料了解。
    

    先看下 () -> new TreeSet<>(Comparator.comparingLong(Quota::getScId))这段代码

       /**
         * Constructs a new, empty tree set, sorted according to the specified
         * comparator.  All elements inserted into the set must be <i>mutually
         * comparable</i> by the specified comparator: {@code comparator.compare(e1,
         * e2)} must not throw a {@code ClassCastException} for any elements
         * {@code e1} and {@code e2} in the set.  If the user attempts to add
         * an element to the set that violates this constraint, the
         * {@code add} call will throw a {@code ClassCastException}.
         *
         * @param comparator the comparator that will be used to order this set.
         *        If {@code null}, the {@linkplain Comparable natural
         *        ordering} of the elements will be used.
         */
    	/**
    	  * 构造一个新的空树集,按照指定的比较器相互比较后放入。后面说的是比较规则不满足抛一个
    	  * ClassCastException
    	  */
        public TreeSet(Comparator<? super E> comparator) {
            this(new TreeMap<>(comparator));
        }
    

    根据scId生成TreeSet,set又是key不重复的,所以我们达到根据属性去重的目的。

撒花★,°:.☆( ̄▽ ̄)/$:.°★