简体   繁体   中英

Reading a CSV and transposing the contents into an ArrayList

I have a CSV file with values I want to load into an arraylist but there's a trick to it. Here are the CSV contents. Consider these values as all strings for simplicity.

 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.10
 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10 

When I get the arrayList packed I want it to look like this:

 1, 0.1, 1.1
 2, 0.2, 2.2
 3, 0.3, 3.3
 4, 0.4, 4.4
 5, 0.5, 5.5
 6, 0.6, 6.6
 7, 0.7, 7.7
 8, 0.8, 8.8
 9, 0.9, 9.9
 10, 0.10, 10.10

The reason for this is this array list will be loaded into a database, each row is a new row in the database. What this data is is measurements taken over time. For example the first row value 1 is a measurement taken at minute 1, 2 the measurement taken at minute 2, same goes for each row. So each array in the list should be all the values taken at minute 1, the next array/db row is all the measurements taken at minute 2, etc.

Currently I'm just loading it into an arrayList line by line but I don't want to put it into the database that way. Here's my current code;

 int count = 0;
 String file = "C:\\Temp\\loadtest.csv";
 List<String[]> content = new ArrayList<>();
 try (BufferedReader br = new BufferedReader(new FileReader(file))) {
     String line = "";
     while (((line = br.readLine()) != null) && (count <17)) {
          content.add(line.split(";"));
     }
     count++;
  } catch (FileNotFoundException e) {
        //Some error logging
  }

I can't seem to figure out how to handle this so any Java code examples are welcome.

List<List<String>> arrays = Files.lines(Paths.get(path)).map(s -> Arrays.asList(s.split(","))).collect(Collectors.toList());

List<List<String>> collect = IntStream.range(0, arrays.get(0).size()).boxed()
        .map(i -> IntStream.range(0, arrays.size()).boxed()
            .map(j -> arrays.get(j).get(i)).collect(Collectors.toList()))
        .collect(Collectors.toList());

First read it as List of List - using split for it. After that you can transpose it for example like in next line.

So, assuming "1, 0.1, 1.1" would be the first desired string in the array list, this is the code:

public void handleCSV() {
    Path path = Paths.get("C:\\Temp\\", "loadtest.csv");

    Charset charset = Charset.forName("ISO-8859-1"); // <- the actual
                                                        // charset of you
                                                        // csv

    List<String> finalLine = new ArrayList<>();

    try {
        List<String> lines = Files.readAllLines(path, charset);

        boolean isFirstLine = true;
        int index = 0;
        for (String line : lines) {
            String[] lineContent = line.split(",");
            for (String column : lineContent) {
                if (isFirstLine) {
                    finalLine.add(column);
                } else {
                    String myEntry = finalLine.get(index);
                    myEntry.concat("," + column);
                    finalLine.set(index, myEntry);
                }
                index++; // adding an index for each element in the row
            }
            index = 0;
            isFirstLine = false;
        }
    } catch (IOException e) {
        System.out.println(e);
    }
}

This code should produce the results you want if every line has the same number of entries

After you have loaded the content of the file into your arrayList you can do something similar to matrix transposing to swap rows and columns. Assuming you want the result to be in a list with string arrays again, and also assuming that your rows have always the same length:

public static void main(String[] args) {
   List<String[]> content = new ArrayList<>();
   content.add(new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"});
   content.add(new String[]{"0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9", "0.10"});
   content.add(new String[]{"1.1", "2.2", "3.3", "4.4", "5.5", "6.6", "7.7", "8.8", "9.9", "10.10"});
   transpose(content).stream().forEach(row ->{System.out.println(Arrays.toString(row));});       
}
public static List<String[]> transpose(List<String[]> list){
    String[][] temp = new String[list.get(0).length][list.size()];
    for (int i = 0; i < list.size(); i++)
        for (int j = 0; j < list.get(0).length; j++)
            temp[j][i] = list.get(i)[j];
    return Arrays.stream(temp).collect(Collectors.toList());
}
 def transposeArrayList(ArrayList<String> targetArray) {

     List resultArray = new ArrayList<>()
     for(int i=0; i<targetArray.size(); i++) {   // this is up to the number of arrays in the list
         // iterate over all the arrays
         for(j=0; j<targetArray.get(i).size(); j++) {
             // if we are ele 0 then we need to create an array list
             if (i == 0) {
                 resultArray.add(new ArrayList())
                 System.out.println("dest = " + resultArray)
                 System.out.println("i is " + i + ", j is " + j)
             }
             ArrayList arrToAddTo = resultArray.get(j)
             ArrayList arrToAddFrom = targetArray.get(i)
             Object objToAdd = arrToAddFrom.get(j)
             arrToAddTo.add(objToAdd)
         }
     }
     System.out.println("original = " + targetArray)
     System.out.println("dest = " + resultArray)
     return resultArray
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM