I am trying Converting a list of objects to a set of objects to make sure if there is no duplicates exists in the collection. I am trying it using Streams.
I have a class Product as below :
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;
}
}
I am trying something Like:
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));
I want the resultant to be stored as Set:
Set<Product> productPriceList=productsList.stream()
.map(p->new Product(p.getId,p.getName,p.getPrice))
.collect(Collectors.toSet());
But it's not working for me. Any suggestions would be highly appriciated !