package com.mkyong.util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ReadFromCVS {

    ArrayList<datas> dataList = new ArrayList<datas>();

    public static void main(String[] args) {

        ReadFromCVS obj = new ReadFromCVS();
        obj.run();
        obj.printDataList(obj.dataList);



    }

    public void run() {
        String csvFile = "C:\\Users\\User\\Downloads\\SalesData.csv";
        BufferedReader br = null;
        String csvSplitBy = ",";
        String line = "";

        try {
            br = new BufferedReader(new FileReader(csvFile));
            br.readLine();
            while ((line = br.readLine()) != null) {

                // split on comma
                String[] datas = line.split(csvSplitBy);

                // crate data object to store values
                datas dataObject = new datas();

                // add values from the csv file to data object
                dataObject.setProductId(Integer.parseInt(datas[0]));
                dataObject.setUnits(Integer.parseInt(datas[1]));

                // adding data object to a list
                dataList.add(dataObject);
            }
            // print values stored in a datalist
            Collections.sort(dataList);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void printDataList(List<datas> dataListToPrint) {
        for (int i = 0; i < dataListToPrint.size(); i++) {
            System.out.println("Product ID: " + dataListToPrint.get(i).getProductId() + " Units: "
                    + dataListToPrint.get(i).getUnits());
        }
    }
}

class datas implements Comparable<datas> {
    private int productId;
    private int units;

    public int getProductId() {
        return productId;
    }

    public void setProductId(int productId) {
        this.productId = productId;
    }

    public int getUnits() {
        return units;
    }

    public void setUnits(int units) {
        this.units = units;
    }

    @Override
    public int compareTo(datas d) {
        if (this.getProductId() > d.getProductId()) {
            return 1;
        } else if (this.getProductId() < d.getProductId()) {
            return -1;
        } else {
            return 0;
        }
    }

}

what ia trying to do is read csv file( contains (product Id and units) and put them in arraylist of objects, then sort the arraylist in ascending order, then I have to look for duplicate product id and add the units to same single product id so their will be no duplicate in the second arraylist.. i am having trouble creating second arraylist and moving the unique products and adding the duplicate product id units to the same unique id units.. please help me

This the out put i get so far:
Product ID: 10001 Units: 5
Product ID: 10001 Units: 8
Product ID: 10001 Units: 7
Product ID: 10002 Units: 4
Product ID: 10002 Units: 10
Product ID: 10002 Units: 6
Product ID: 10003 Units: 8
Product ID: 10003 Units: 6
Product ID: 10003 Units: 3
Product ID: 10003 Units: 7
Product ID: 10003 Units: 4
Product ID: 10004 Units: 6
Product ID: 10004 Units: 9

Dani AI

Generated

Short answer for : sorting the list won't remove duplicates — aggregate by productId instead. Two concise, practical options follow: one that builds a simple Map of totals (works well and is easy to reason about) and one that reuses your existing datas objects to avoid extra allocations.

Method 1 — aggregate into a Map (Java 8+)

Map<Integer,Integer> totals = new LinkedHashMap<>();
for (datas d : dataList) {
    totals.merge(d.getProductId(), d.getUnits(), Integer::sum);
}
// build merged list
List<datas> merged = new ArrayList<>();
for (Map.Entry<Integer,Integer> e : totals.entrySet()) {
    datas dd = new datas();
    dd.setProductId(e.getKey());
    dd.setUnits(e.getValue());
    merged.add(dd);
}
Collections.sort(merged); // optional

Method 2 — keep one object per productId (in-place summing)

Map<Integer,datas> byId = new LinkedHashMap<>();
for (datas d : dataList) {
    datas exist = byId.get(d.getProductId());
    if (exist == null) {
        byId.put(d.getProductId(), d); // adopt the object you already created
    } else {
        exist.setUnits(exist.getUnits() + d.getUnits());
    }
}
List<datas> merged = new ArrayList<>(byId.values());
Collections.sort(merged); // if you still want ascending order

Notes and cautions

  • If you read a very large CSV, aggregate while reading (update the Map inside the read loop) to avoid holding every row in memory twice.
  • Use LinkedHashMap if you want to preserve input order; HashMap if order doesn't matter.
  • Trim and validate CSV fields before parseInt to avoid NumberFormatException.
  • Consider renaming datas to a clearer class name (e.g., ProductData) and, if you ever use sets, implement equals/hashCode based on productId.

Either approach yields one entry per productId with units summed, O(n) time.

What help do you need exactly? Where are you stuck?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.