java8 Stream 一行代码实现列表去重
程序员文章站
2022-07-12 22:07:28
...
通常情况下,实现列表去重的方式有:
- 创建一个新的result列表,循环原列表,如果元素不在result列表中,则放入
- 创建一个HashSet,将列表作为构造参数传入
下面介绍一种简单、高效的去重方式,借助于java8新特性引入的Stream类。代码如下
package cn.zokoo.goods.entity.dto; import java.io.Serializable; import java.util.Date; import java.util.List; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * 商品分类 * * @author Jack chen * @email 123@qq.com * @date 2018-12-10 17:14:36 */ @Data @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class MchCatDTO implements Serializable { private static final long serialVersionUID = 1L; /** * 分类编号 */ private Integer catId; /** * 分类编码 */ private String catCode; /** * 分类名称 */ private String catName; /** * 上级分类编码 */ private String parentCatCode; /** * 排序 */ private Integer sortOrder; // 商户号 private String mchNo; //新增类型 1-导入 2-普通品类 3-活动品类 private String catType; /** * 分类图标 */ private String catIcon; /** * 是否显示:0-否 1-是 */ private String isShow; /** * 备注 */ private String remark; /** * 版本号 */ private Integer version; /** * 创建时间 */ private Date createTime; /** * 创建操作员 */ private String createOprNo; /** * 修改时间 */ private Date modifiedTime; /** * 修改操作员 */ private String editOprNo; private List<MchCatDTO> childList; private Long count; public MchCatDTO(String catCode, String parentCatCode) { this.catCode = catCode; this.parentCatCode = parentCatCode; } public MchCatDTO(String catCode, String parentCatCode,String catName) { this.catCode = catCode; this.parentCatCode = parentCatCode; this.catName = catName; } public MchCatDTO(Integer catId, String catCode, String catName, Integer sortOrder, String catIcon) { this.catId = catId; this.catCode = catCode; this.catName = catName; this.sortOrder = sortOrder; this.catIcon = catIcon; } public MchCatDTO(String catCode,String catName,String parentCatCode,Long count,String catType,Date createTime) { this.catCode = catCode; this.parentCatCode = parentCatCode; this.catName = catName; this.count = count; this.catType = catType; this.createTime = createTime; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MchCatDTO cat = (MchCatDTO) o; return Objects.equals(this.catCode, cat.catCode) && Objects.equals(this.catName, cat.catName); } @Override public int hashCode() { return Objects.hash(this.catCode,this.catName); } }
去重解决:catList = catList.stream().distinct().collect(Collectors.toList());