stream流自定义去重
时间: 2025-02-23 07:57:00 浏览: 72
### 实现自定义对象流 `distinct()` 方法
为了在 Java Stream API 中实现自定义去重逻辑,可以利用 `filter` 结合哈希集合来去除重复项。对于复杂对象而言,通常通过指定某个字段作为唯一标识来进行比较。
下面是一个完整的例子,展示如何基于特定属性对自定义类的对象列表执行去重操作:
```java
import java.util.*;
import java.util.stream.Collectors;
class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Product)) return false;
Product product = (Product) o;
return Double.compare(product.price, price) == 0 && Objects.equals(name, product.name);
}
@Override
public int hashCode() {
return Objects.hash(name, price);
}
@Override
public String toString() {
return "Product{name='" + name + "', price=" + price + '}';
}
}
public class DistinctCustomObjects {
public static void main(String[] args) {
List<Product> products = Arrays.asList(
new Product("Apple", 1.2),
new Product("Banana", 0.5),
new Product("Orange", 0.7),
new Product("Apple", 1.2), // Duplicate item based on both fields
new Product("Grape", 2.0)
);
Set<String> seenNames = new HashSet<>();
List<Product> distinctProductsByNameAndPrice = products.stream()
.filter(p -> seenNames.add(p.getName() + p.getPrice()))
.collect(Collectors.toList());
System.out.println(distinctProductsByNameAndPrice);
// Alternatively using a more complex approach with grouping by multiple properties and then mapping back to list.
Map<String, Optional<Product>> groupedDistinct =
products.stream().collect(Collectors.groupingBy(p -> p.getName() + "-" + p.getPrice(),
Collectors.reducing((p1, p2) -> p1)));
List<Product> finalDistinctList = groupedDistinct.values().stream()
.map(Optional::get).collect(Collectors.toList());
System.out.println(finalDistinctList);
}
}
```
在这个案例中,首先创建了一个简单的 `Product` 类并覆写了其 `equals` 和 `hashCode` 方法以便于后续的操作能够正确识别相同的实例[^1]。接着,在主函数里展示了两种不同的方式来达到相同的目的——移除具有相同志愿名称和价格的产品条目。
阅读全文
相关推荐


















