CSV ファイルの内容を連想配列(HashMap)にします。
selectColumn.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
public class selectColumn {
public static void main(String[] args) {
// read CSV file
HashMap<List<String>, String> tbl = readCSVFile("data.csv");
// set the keys for selection
Map<String, String> oldMap = new HashMap<>();;
oldMap.put("suzuki", "aiueo");
Map<String, String> newMap = new HashMap<>();;
newMap.put("suzuki", "kkkkk");
// select
oldMap.forEach(
(key, value) -> {
if (newMap.containsKey(key)) {
String matched = tbl.get(Arrays.asList(key, value, newMap.get(key)));
System.out.println(matched == null ? "None matched" : matched);
}
});
}
// readCSVFile returns HashMap instance
// key: first, second and third column (name, old, new)
// value: 4th column
public static HashMap<List<String>, String> readCSVFile(String pathToCsv) {
HashMap<List<String>, String> rows = new HashMap<>();
try {
File file = new File(pathToCsv);
BufferedReader csvReader = new BufferedReader(new FileReader(file));
csvReader.readLine(); // skip header line
String row;
while ((row = csvReader.readLine()) != null) {
String[] items = row.split(",");
rows.put(
Collections.unmodifiableList(
Arrays.asList(Arrays.copyOfRange(items, 0, items.length-1))),
items[items.length-1]);
}
csvReader.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
return rows;
}
}
data.csv
name,old,new,
suzuki,aiueo,kkkkk,konnitiha
seigo,aiueo,ttttt,kontiwa
suzuki,kkkkk,aiueo,majimaji
hukko,ttttt,sssss,ohohohoho
実行結果
$ javac selectColumn.java && java selectColumn
konnitiha