-1

I am a new bee in Java and want to map CSV columns according to their values. My orignal csv data is like:

 name,salary,address
 AAA,1000,kkk
 BBB,880,lll
 AAA,90,kkk
 CCC,700,mmm
 BBB,700,lll

Expected output should be in Hashmap Key Value pair of two columns name and salary like:

Key: AAA Value 1090
Key: BBB Value 1580
Key: CCC Value 700

This is my code:

        String line = "";
 InputStreamReader inStream = new 
       InputStreamReader(uc.getInputStream());
        buff = new BufferedReader(inStream);  
         try {
            while ((line = b.readLine()) != null) {
                String[] fields = parseCsvLine(line);

                // I dont know what to do here



            }


            b.close();
            Log.d("Get data from API", "Processing Stop");
        } catch (IOException e) {
            e.printStackTrace();
        }

 public  String[] parseCsvLine(String line) {
    // Create a pattern to match breaks
    Pattern p =
            Pattern.compile(",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))");
    // Split input with the pattern
    String[] fields = p.split(line);
    for (int i = 0; i < fields.length; i++) {
        // Get rid of residual double quotes
        fields[i] = fields[i].replace("\"", "");
    }
    return fields;
}
3
  • Looks like you need to create your Map and put the map.put(fields[0], fields[1]);. Commented May 18, 2018 at 14:25
  • I want to map each name in csv with sum of its salaries. Commented May 18, 2018 at 14:26
  • You should use csv parser. Try commons.apache.org/proper/commons-csv Commented May 18, 2018 at 14:31

1 Answer 1

0

What you want is to split your line data into part. Then accumulate it to a Map

Map<String, Integer> result = new HashMap<>();

while ((line = b.readLine()) != null) {
   String[] parts = line.split(","); // Split your line, take `,` as delimeter
   String key = parts[0]; // This is your 'AAA'
   Integer value = Integer.parseInt(parts[1]); // This is your 1000
   if (result.get(key) == null) {
       result.put(key, value); 
   } else {
       result.put(key, result.get(key) + value); // There's already a value here, add it with new value
   }


}

The ugly part:

   if (result.get(key) == null) {
       result.put(key, value); 
   } else {
       result.put(key, result.get(key) + value); // There's already a value here, add it with new value
   }

Can replaced with new Java 8 Map utility:

 result.putIfAbsent(key, value); // Put (key, value) if key is absent from the map
 result.compute(key, value, (k, v) -> v + value);
Sign up to request clarification or add additional context in comments.

21 Comments

Thanks, I am trying and let you know its working.
[@user2778724] You're welcome~.
The String[] parts = line.split(","); won't work for all cases, because the values can also contain commas. Such values are usually quoted, so it's better to use a csv parser here. Try commons-csv or opencsv.
It's match with OP's format. Seriously, if the delimiter is not known beforehand, how did you split it??????? As openCSv use some common delimiter like tab, space, ... only. Add an entire library to just to read a simple file? lol. You made my day.
@Mạnh Quyết Nguyễn I have tried your code but displaying result give me following output {AAA=1000 90, BBB=880 700, CCC=700}
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.