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());