I have a collection of Products that I want to transform into a HashMap based on the productCode, which is an identifier in the Product object. However, it does not seem to work, from following examples I saw. Can someone point out what I’m doing wrong?
Here is the code in it’s entirety:
import lombok.Builder;
import lombok.Data;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import static java.util.function.UnaryOperator.identity;
@Data
public class Product {
private String productCode;
private String productDescription;
private BigDecimal unitCost;
private BigDecimal bulkPrice;
@Builder
public Product(String productCode, String productDescription, BigDecimal unitCost,
BigDecimal bulkPrice) {
this.productCode = productCode;
this.productDescription = productDescription;
this.unitCost = unitCost;
this.bulkPrice = bulkPrice;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Product product = (Product) o;
return Objects.equals(productCode, product.productCode);
}
@Override
public int hashCode() {
return Objects.hash(productCode);
}
public static void main(String[] args) {
List<Product> products = new ArrayList<>();
Product musk1 = new Product("FRAGMusk001", "Men's fragrance", BigDecimal.valueOf(9.00), BigDecimal.valueOf(7.99));
Product musk2 = new Product("FRAGMusk001", "Men's fragrance", BigDecimal.valueOf(9.00), BigDecimal.valueOf(7.99));
Product dior = new Product("FRAGDior877", "Men's mid range cologne", BigDecimal.valueOf(9.00), BigDecimal.valueOf(7.99));
Product paccoRabane = new Product("FRAGRabbne442", "Men's mid range cologne", BigDecimal.valueOf(9.00), BigDecimal.valueOf(7.99));
Product verricio = new Product("FRAGVeri556", "Men's elite cologne", BigDecimal.valueOf(9.00), BigDecimal.valueOf(7.99));
products.add(musk1);
products.add(musk2);
products.add(dior);
products.add(paccoRabane);
products.add(verricio);
// This does not work
Map<String, Product> productMap = products.stream().distinct().collect(Collectors.toMap(product -> product.getProductCode()));, identity()));
}
}
>Solution :
product.getProduct() isn’t a method in product. Presumably you meant product -> product.getProductCode(), or simpler: Product::getProductCode.
Note that you don’t have to write that equals and hashcode method; just stick @EqualsAndHashCode.Include on your productCode field and delete hashCode and equals – then lombok will take care of it for you.