Java 8. Casting Object[] to String[][]

后端 未结 2 1735
孤城傲影
孤城傲影 2021-01-20 05:51

I\'m trying to load data from file into JTable. So, using Java 8 streams it is very easy to load file into array of strings:

BufferedReader br = new Buffered         


        
相关标签:
2条回答
  • 2021-01-20 06:38

    Splitting that piece of casting out into a loop should do it.

    BufferedReader br = new BufferedReader(new FileReader(f));
    Object[] data = br.lines().map((s)->{
            String[] res = {s,"1"}; // Here's some conversion of line into String[] - elements of one row
            return res;
        }).toArray();
    
    String[][] dataMatrix = new String[data.length][];
    for(int i = 0; i < data.length; i++){
        dataMatrix[i] = (String[]) data[i];
    }
    TableModel m = new DefaultTableModel(dataMatrix, cols);
    
    0 讨论(0)
  • 2021-01-20 06:40

    If you use toArray(String[][]::new) instead of toArray() it will return a String[][] instead of an Object[] and you wont need to cast it at all (if you assign it to a String[][]).

    0 讨论(0)
提交回复
热议问题