I have such a product class.
@Data
public class Product {
private UUID id;
private String name;
private String categoryName;
private String frontName;
}
And I have a list of products - some product names are the same even though they have different category.I need to do the following for products that have the same names: product.setFrontName(product.getName() "," product.getCategoryName())
And for products with unique names, it's just to do: product.setFrontName(product.getName())
I tried various options with streams, but in the end I could not find a solution.
Could you share a more efficient solution to this task. Thank you.
CodePudding user response:
please see the following code:
Set<String> items = new HashSet<>()
Set<String> duplicateProduct = productList.stream()
.filter(p -> !items.add(p.name)).map(Product::getName) // Set.add() returns false if the element was already in the set.
.collect(Collectors.toSet());
productList.forEach( p ->{
if(duplicateProduct.contains(p.getName())){
p.setFrontName(p.getName() "," p.getCategoryName());
} else {
p.setFrontName(p.getName());
}
});
CodePudding user response:
There's a few ways you can approach a solution.
My first idea is for example say that you have a List< Product> containing all the products, then you need to:
Iterate through all the products and save each product by name in a Map<String, List< Product>>. Products under the same name should be stored in the List< Product> value that has the name as key.
Iterate through all the entries of this map and check if the size of the list is greater than 1, it means the product has duplicate (or more) name with other products. Otherwise it's unique.