Java 8 Streams:将对象列表转换为一组对象

Naw*_*zSE 5 java java-8 java-stream

我正在尝试将对象列表转换为一组对象,以确保集合中不存在重复项。我正在尝试使用 Streams。

我有一个类产品如下:

class Product{  
int id;  
String name;  
float price;  
public Product(int id, String name, float price) {  
    this.id = id;  
    this.name = name;  
    this.price = price;  
}  
 public String getName()
 {
     return this.name;
 }
 public int getId()
 {
     return this.id;

 }
 public float getPrice()
 {
     return this.price;
 }
 public void setName(String name)
 {
     this.name = name;
 }
 public void setId(int id)
 {
     this.id = id;
 }
 public void getPrice(float price)
 {
     this.price = price;
 }
}  
Run Code Online (Sandbox Code Playgroud)

我正在尝试类似的东西:

   List<Product> productsList = new ArrayList<Product>();  

    //Adding Products  
    productsList.add(new Product(1,"HP Laptop",25000f));  
    productsList.add(new Product(2,"Dell Laptop",30000f));  
    productsList.add(new Product(3,"Lenevo Laptop",28000f));  
    productsList.add(new Product(4,"Sony Laptop",28000f));  
    productsList.add(new Product(5,"Apple Laptop",90000f));  
    productsList.add(new Product(5,"Apple Laptop",90000f)); 
Run Code Online (Sandbox Code Playgroud)

我希望将结果存储为 Set:

 Set<Product> productPriceList=productsList.stream()
 .map(p->new Product(p.getId,p.getName,p.getPrice))
 .collect(Collectors.toSet()); 
Run Code Online (Sandbox Code Playgroud)

但这对我不起作用。任何建议都将受到高度评价!

Mic*_*ael 6

您的代码几乎可以编译,您只是错过了括号p.getId等:

Set<Product> productPriceList = productsList.stream()
    .map(p -> new Product(p.getId(), p.getName(), p.getPrice()))
    .collect(Collectors.toSet());
Run Code Online (Sandbox Code Playgroud)

但是,如果您希望该集合正常工作,则Product必须覆盖。你可以看到这个问题为什么。equalshashCode