簡體   English   中英

使用主鍵對2D數組排序

[英]Sort a 2D Array with primary key

我正在嘗試拆分文本文件的每一行並插入到數組列表中。

aa 04 cc ff gg rrr
aa 01 bb dd ee fff
aa 03 ff hh ee ttt
aa 05 dd ss ww ccc

1,如何將數字存儲為整數,其余的是數組列表中的字符串。 (使用當前代碼引發數字格式錯誤)。

2,當我使用Java集合插入數組時,是否可以基於整數排序?

到目前為止,我已經

List <Object> records = new ArrayList<Object>();
        bf = new BufferedReader(new FileReader(getFile()));
        String readLine;        

        while ((readLine = bf.readLine()) != null) {
            try {
                    List <Object> record = new ArrayList<Object>();

                    record.add(readLine.substring(flg_start, num_start).trim());
                    record.add(Integer.parseInt(readLine.substring(num_start-1, fld_start-1).trim())); // converting string to int and saving to record list, throwing Number Format Error.

讓我再次表述我的問題:如何將記錄[1]設置為整數,如何將其設置為字符串? 將數組添加到數組時可以使用哪種收集框架進行排序? 我期望數組中的最終結果是大約1M條記錄的排序列表

aa 01 bb dd ee fff
aa 03 ff hh ee ttt
aa 04 cc ff gg rrr
aa 05 dd ss ww ccc

至於數據結構,則需要帶Integer鍵和List值的TreeMap 您應該閱讀文件並按@HaridwarJha所述解析每一行,並為每一行添加新值,其中包含解析后的Integer鍵和由解析后的值形成的List值。 使用TreeMap您的數據將按鍵(即文件中的Integer值)進行排序。

Map<Integer, List<Object>> map = new TreeMap<Integer, List<Object>>();
while((line=reader.readLine())!=null){
    List<Object> row = new ArrayList<>();
    String[] strArray=line.split(" ");
    row.add(strArray[0]);
    row.add(strArray[1]);
    row.add(strArray[2]);
    row.add(strArray[3]);
    row.add(strArray[4]);
    row.add(strArray[5]);
    map.put(new Integer(row.get(1)), row);
}

您可以這樣做,並訪問strArray,可以將其用於循環,也可以使用regex [0 ... 1]進行解析。...這很簡單...嘗試使用public static void main(String [] args ){列表記錄= new ArrayList();

    File file=new File("File Location");
    try {
        BufferedReader reader=new BufferedReader(new FileReader(file));
        String line;
        while((line=reader.readLine())!=null){
            String[] strArray=line.split(" ");
            records.add(new Integer(strArray[1]));
            records.add(new String(strArray[0]));
            records.add(new String(strArray[2]));
            records.add(new String(strArray[3]));
            records.add(new String(strArray[4]));
            records.add(new String(strArray[5]));
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    for(Object tmp:records){
        System.out.println(tmp);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM