zoukankan      html  css  js  c++  java
  • java List 去重

    1.使用 jdk8 中 stream.distinct().collector

    需要重写实体类中的 equals()和hashCode()方法

    @Data
    @EqualsAndHashCode(callSuper = true)
    @Accessors(chain = true)
    public class SyncDataNodeInfo extends BaseEntity {
    
        private static final long serialVersionUID = 1L;
        /**
         * 当前节点ID
         */
        private String nodeId;
    
        /**
         * 当前节点name
         */
        private String currentNodeName;
    
    
        @Override
        public boolean equals(Object o){
            if(this == o){
                return true;
            }
            if(o == null || getClass() != o.getClass()){
                return false;
            }
            SyncDataNodeInfo syncDataNodeInfo = (SyncDataNodeInfo) o;
            return nodeId.equals(syncDataNodeInfo.nodeId);
        }
    
        @Override
        public int hashCode(){
            return Objects.hash(nodeId);
        }
    }
    
    public static void main(String[] args) {
            List<SyncDataNodeInfo> newSyncDataNodeInfoList = new ArrayList<>();
            SyncDataNodeInfo syncDataNodeInfo = new SyncDataNodeInfo();
            syncDataNodeInfo.setParentNodeId("111");
            syncDataNodeInfo.setCurrentNodeName("zzz");
            newSyncDataNodeInfoList.add(syncDataNodeInfo);
            
            newSyncDataNodeInfoList.stream().distinct().collect(Collectors.toList());
        }
    

      

     针对 List中的String和普通的int,long等可以直接使用,不需要重写equals和hashCode方法

    stream().distinct().collect(Collectors.toList());

  • 相关阅读:
    leetcode-409
    leetcode-836
    leetcode-1160
    leetcode-面试题13
    leetcode-695
    go的一些小lib
    leetcode-300
    cookie
    php上传文件
    PHP 文件创建/写入
  • 原文地址:https://www.cnblogs.com/pass-ion/p/14246616.html
Copyright © 2011-2022 走看看