0
私はCSV形式のテーブルデータを持っています。最初の行はすべての列名(キー)およびそれ以降のすべての行を含む、以下のように記録(値)は以下のとおりです。キーを使用せずにLinkedHashMapに値を挿入する
ID,Name,Contact,Address
1,Alex,987654321,CA USA
2,Bob,4489398,LA USA
3,Marley,7236487,Washington
私はこのファイルを読み取り、のLinkedHashMapでキーと値のペアとしてレコードを格納しようとしています。ここで私がしようとしていることを示すためのコードです。私の質問はコメントとしてコードに書かれています。
public static void readCSV() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("table.csv"));
Map<String, ArrayList<String>> map = new LinkedHashMap<>();
String line = br.readLine();
String[] keys = line.split(",");
/*insert all keys with a corresponding empty arraylist as value to store
all values of a particular key. ie each arralist will contain all values
of individual columns. Since it is a linkedhashmap, keys are stored in
same order as they appear in the csv file*/
for (String key : keys) {
map.put(key, new ArrayList<String>());
}
while((line = br.readLine())!=null){
String[] values = line.split(",");
for (String value : values) {
/*here I want to get the arraylists sequentially to store value.
I know the first value goes in the first arraylist, second goes
to second arraylist and so on.
Is there a way to do this without using the key here??
*/
}
}
}
なぜこのようなデータ構造ではなく、マップキー - > columnIndexにして 'String []型'(1のリスト行ごとに)? – fabian
すべての行をカスタムオブジェクトに解析してリストに入れる方がよい場合があります。 – davioooh