Read a csv file and process the data

  • #1
239
17
TL;DR Summary
Hi i need some help in this portion of code, i have no clue what it does... in particular the highlighted portion
Java:
public static Region fromFile(String name, String file) {
        Region r = new Region(name);
        List<String> lines = readData(file);
        
        String[] headers = lines.remove(0).split(";");
        Map<String, Integer> h2i = new HashMap<>();
        for (int i=0; i<headers.length; i++) {
            h2i.put(headers[i], i);
        }
        
        lines.forEach(l -> {
            String[] rows = l.split(";");
            
            String provinceName = rows[h2i.get("Province")];
            String municipalityName = rows[h2i.get("Municipality")];
            Integer municipalityAltitude = Integer.parseInt(rows[h2i.get("MunicipalityAltitude")]);
            
            Municipality municipality = r.createOrGetMunicipality(municipalityName,
                                                    provinceName, municipalityAltitude);
            
            String mh_name = rows[h2i.get("Name")];
            String altitude = rows[h2i.get("Altitude")];
            String category = rows[h2i.get("Category")];
            Integer bedsNumber = Integer.parseInt(rows[h2i.get("BedsNumber")]);
            
            
            if (altitude.equals("")) {
                r.createOrGetMountainHut(mh_name, category, bedsNumber, municipality);
            } else {
                r.createOrGetMountainHut(mh_name, Integer.parseInt(altitude), category, bedsNumber, municipality);
            }       
        });
        
        return r;
    }
 
  • #2
My Java is a bit rusty. But the code looks very readable to me. This is what it does:
  1. Read the data from a file into an array of strings, where each entry represents a single line in the data file.
  2. Extract the first line (I assume that is what Array.remove(0) does) and split it into an array of semicolon-separated header entries.
  3. Create a map M : "header entry" -> "column index" for future use
  4. For each line in the remaining lines:
    1. Get the array of semicolon-separated entries (counter-intuitively, the array is called "rows")
    2. Get the index of the column with the header "Province", read the entry at this location, and store it in the variable "provinceName".
    3. Do the equivalent for municipalityName and municipalityAltitude (in the 2nd case also convert the string to an integer)
    4. (Do some other stuff in the part of the code that is not highlighted)
 

Suggested for: Read a csv file and process the data

Replies
34
Views
2K
Replies
9
Views
1K
Replies
3
Views
882
Replies
10
Views
921
Replies
14
Views
3K
Replies
1
Views
163
Replies
8
Views
930
Replies
3
Views
710
Back
Top