You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java/Kotlin算法问题:合并ArrayList中重复Product对象并累加数量

Merge Duplicate Products by ID and Sum Quantities

Hey there! This is a super common scenario when working with product lists, and using a Map is the cleanest, most efficient way to handle it—since maps enforce unique keys, we can leverage the product ID as our key to group duplicates and sum up their quantities.

Step-by-Step Solution

Let’s break this down with Java code (since you mentioned ArrayList and Product objects, I’m assuming a Java context):

  1. First, let’s confirm your Product class structure (adjust if your fields/methods differ slightly):
public class Product {
    private int id;
    private String name;
    private int quantity;

    // Constructor
    public Product(int id, String name, int quantity) {
        this.id = id;
        this.name = name;
        this.quantity = quantity;
    }

    // Getters and Setters
    public int getId() { return id; }
    public String getName() { return name; }
    public int getQuantity() { return quantity; }
    public void setQuantity(int quantity) { this.quantity = quantity; }

    // Optional: toString() for easy debugging output
    @Override
    public String toString() {
        return "Product{id=" + id + ", name='" + name + "', quantity=" + quantity + "}";
    }
}
  1. Merge logic using a HashMap
    We’ll loop through your original ArrayList<Product>, use the product ID as the map key, and either add new products or update the quantity for existing duplicates:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ProductMerger {
    public static ArrayList<Product> mergeDuplicateProducts(ArrayList<Product> originalList) {
        Map<Integer, Product> productMap = new HashMap<>();

        for (Product product : originalList) {
            int productId = product.getId();
            if (productMap.containsKey(productId)) {
                // Duplicate found: sum the quantities
                Product existingProduct = productMap.get(productId);
                existingProduct.setQuantity(existingProduct.getQuantity() + product.getQuantity());
            } else {
                // New product: add to map (we create a copy here to avoid modifying original objects)
                productMap.put(productId, new Product(product.getId(), product.getName(), product.getQuantity()));
            }
        }

        // Convert the map's values back to an ArrayList
        return new ArrayList<>(productMap.values());
    }

    // Test the functionality with your example
    public static void main(String[] args) {
        ArrayList<Product> products = new ArrayList<>();
        products.add(new Product(1, "Computer", 3));
        products.add(new Product(1, "Computer", 7));
        products.add(new Product(2, "Keyboard", 2));
        products.add(new Product(2, "Keyboard", 4));

        ArrayList<Product> mergedProducts = mergeDuplicateProducts(products);
        mergedProducts.forEach(System.out::println);
        // Expected output:
        // Product{id=1, name='Computer', quantity=10}
        // Product{id=2, name='Keyboard', quantity=6}
    }
}

Key Details to Keep in Mind:

  • Efficiency: HashMap gives O(1) average time complexity for lookups and inserts, so this solution works smoothly even for large product lists.
  • Preserve Order: If you need to keep the order of the first occurrence of each product, swap HashMap with LinkedHashMap.
  • Avoid Original Object Changes: In the code above, we create a new Product when adding to the map. If you don’t mind modifying the original list’s objects, you can skip the copy and add the original product directly.
  • Name Consistency: This assumes products with the same ID always have the same name. If there’s a chance of mismatched names for the same ID, add a check (like a warning log or exception) to handle that edge case.

内容的提问来源于stack exchange,提问作者Mickael Belhassen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:00:28