如何分组并删除重复的对象

时间:2019-12-10 06:00:14

标签: java dictionary kotlin

我有这个Item类:

data class Product(val id: Long, val name: String, val region: Long)

给出列表List<Product>

Product(1, "Product 1", 1)
Product(1, "Product 1", 1)
Product(1, "Product 1", 2)
Product(2, "Product 2", 1)

您可以看到同一产品可以多次添加到同一区域。我想对productList.groupBy { it.region }之类的区域进行分组,但是在生成的地图条目中,我想删除具有相同ID的产品。

2 个答案:

答案 0 :(得分:3)

productList.groupBy { it.region }.mapValues { it.distinctBy { it.id } }

mapValues

  

返回一个新映射,其中包含具有该映射键和通过将变换函数应用于此映射中的每个条目而获得的值的条目。

distinctBy

  

返回一个列表,该列表仅包含给定集合中具有给定选择器函数返回的不同键的元素。

答案 1 :(得分:0)

为了实现这一点,我们需要覆盖hash类中的equalsProductInfo方法,然后在流api下应用

 Map<Integer,List<ProductInfor>> map=list.stream()
.distinct()
.collect(Collectors.groupingBy(ProductInfo::getId,Collectors.toList()))

有关完整代码,请通过下面的内容

   import java.util.stream.*;
import java.util.*;

class ProductInfo{
private Integer id;
private String product;
private Integer region;

public Integer getId(){
    return id;
}

public String getProduct(){
    return product;
}

public Integer getRegion(){
    return region;
}

public ProductInfo(Integer id,String product,Integer region){

    this.id=id;
    this.product=product;
    this.region=region;
}

@Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        ProductInfo that = (ProductInfo)o;
        return Objects.equals(getId(), that.getId()) && Objects.equals(getProduct(), that.getProduct()) && Objects
            .equals(getRegion(), that.getRegion());
    }

    @Override
    public int hashCode() {
        return Objects.hash(getId(), getProduct(), getRegion());
    }


    public String toString(){
        return "id="+this.getId()+" product="+this.getProduct()+" region="+getRegion();
    }
}

public class Test{
    public static void main(String args[]){
        List<ProductInfo> list=Arrays.asList(new ProductInfo(1,"product1",1),new ProductInfo(1,"product1",1),new ProductInfo(2,"product2",2));
        System.out.println(list.stream().distinct().collect(Collectors.groupingBy(ProductInfo::getId,Collectors.toList())));
    }
}
相关问题