我有一些 bean 类型(产品)的列表,我需要找到列表中重复的产品,假设我的 bean Products 包含像这样的 getter 和 setter
public class Product {
private int id;
private String name;
private BigDecimal cost;
private int uniqueAssignedId;
public Product(int id, String name, BigDecimal cost, int uniqueAssignedId) {
this.id = id.....
}
public int getId() {
return this.id;
}
//The rest of getters and setters.
我试图将此列表放入 map 中以查找重复的“id”值,但它没有按我的预期工作,问题是我的列表是已售产品的列表(抱歉冗余)因此,每个售出的产品都有一个唯一的 uniqueAssignedId,因此对象总是不同的,假设我的列表填充如下:
listProducts.add(5, "Soda", 1.00, 1);
listProducts.add(3,"Phone", 300.00, 2);
listProducts.add(4, "Cofee", 5.00, 3);
listProducts.add(5, "Soda", 1.00, 4);
listProducts.add(4, "Cofee", 5.00, 5);
listProducts.add(5, "Soda", 1.00, 6);
(我知道我必须创建一个对象 Product Product = new Product() 并用 setter 填充它,然后将该对象添加到我的列表中,但这更简单)
到目前为止我已经尝试过:
Set<Product> uniqueId = new HashSet<Product>(listProducts);
for (Product product : uniqueId) {
System.out.println("The product with id "+product.getId+" was repeated: "
+ Collections.frequency(listProducts, product.getId));
}
但它总是迭代 6 次而不是 3 次(3 是我销售的不同产品的数量)。那么我怎样才能让Hashset只获得不同的id呢?我应该使用 map 吗?任何线索将不胜感激。
最佳答案
public class ProductComparator implements Comparator<Product>
{
public int compare(Product p1, Product p2)
{
return p1.id-p2.id;
}
}
ArrayList<Product> listProducts = new ArrayList<Product>();
listProducts.add(new Product(5, "Soda", 1.00, 1));
listProducts.add(new Product(3,"Phone", 300.00, 2));
listProducts.add(new Product(4, "Cofee", 5.00, 3));
listProducts.add(new Product(5, "Soda", 1.00, 4));
listProducts.add(new Product(4, "Cofee", 5.00, 5));
listProducts.add(new Product(5, "Soda", 1.00, 6));
System.out.println(listProducts.size()); // Total records
TreeSet<Product> products = new TreeSet<Product>(new ProductComparator());
products.addAll(listProducts);
ArrayList<Product> duplicate = new ArrayList<Product>();
duplicate.addAll(products);
listProducts.removeAll(duplicate);
System.out.println(products.size()); // Now no duplicates in this set.
System.out.println(listProducts.size()); // Now only duplicate in this list
关于java - 将 Collections.Frequency 与 List<SomeBeanType> 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18255476/