当前位置: 首页 > 知识库问答 >
问题:

在List java中获取重复对象

马亮
2023-03-14

我有一份产品清单

List<Product> productList = [product1, product2,product2, product3, product3, product5];

我的产品类别是

public class Product {
 private long productId;
 private String productName;
 private double productPrice;
 ... getters and setters
}

我想要两个列表:第一个只返回多次出现的产品,第二个只返回一次出现的产品

我正在使用Java8中的流

List<Product> productMoreThanOnce = new ArrayList<>();
List<Product> productOnlyOnce = new ArrayList<>();
productMoreThanOnce = productList.stream().filter(e-> Collections.frequency(productList, e) > 1).distinct().collect(Collectors.toList());

productOnlyOnce  = productList.stream().filter(e-> Collections.frequency(productList, e) == 1).distinct().collect(Collectors.toList());

但ProductMorethance不会返回重复的产品=

最好的方法是什么?

共有2个答案

赵奕
2023-03-14

如果您还没有在Products类中添加和重写equals和hashcode方法,请这样做。

@Override
public boolean equals(final Object o) {
    if (this == o) {
        return true;
    }
    if (!(o instanceof Product)) {
        return false;
    }
    final Product product = (Product) o;
    return productId == product.productId && Double.compare(product.productPrice, productPrice) == 0
            && Objects.equals(productName, product.productName);
}

@Override
public int hashCode() {
    return Objects.hash(productId, productName, productPrice);
}

然后,您可以使用streams api中的分区收集器:

Map<Boolean,List<Product>> map = productList.stream()
        .collect(Collectors.partitioningBy(e -> Collections.frequency(productList, e) > 1));

List<Product> productMoreThanOnce = map.get(true);
List<Product> productOnlyOnce     = map.get(false);
云宜人
2023-03-14

您可以在流中分组:

Map<Product, Long> map = productList.stream()
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

这里每个键都有相关联的出现次数作为值。

然后可以检索唯一的元素:

List<Product> unique = map.entrySet().stream()
    .filter(e -> e.getValue() == 1)
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

或重复:

List<Product> duplicate = map.entrySet().stream()
    .filter(e -> e.getValue() > 1)
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());
 类似资料:
  • 我有这个初始数组,希望根据和提取重复航班 我写了这个,但我只能得到第一个重复的,看起来不是很漂亮。 有什么建议吗?

  • 我有这样的json数组 我想得到

  • 假设我有一个具有10个键值的对象, 我只想从对象中获取前5个键值, 就像我们可以在数组中切片并得到前5个元素一样,是否可以为相同的元素做一些事情。 我试图寻找解决方案,但无法找到与之相关的任何内容。 任何帮助都会很有帮助。如果有人需要任何新的细节,请告诉我。

  • 我有如下所示的数据 现在我想获取所有记录的地址,但是当您看到输出时,我将其作为[对象]获取。那么任何人都可以告诉我如何获得地址吗? 这是我的代码: 输出:

  • 我有一串喜欢的 我想得到的数字只从这个字符串喜欢 我如何使用JavaScript得到这个?谢谢:)

  • 我为用户对象创建了如下类: 现在,我正在尝试获取id(例如,当我传递name dog时需要获得100),当我传递字符串other时需要获得75。你知道怎么做吗?