Java读取CSV文件并映射成Map
场景
我们在工作中存在这种场景,需要读取excel表格,表格的第一行为字段名,从第二行开始是对应的值,我们想把从第二行开始的每一行依次与第一行的字段映射成一个map<key, value>的格式,方便以后进行方法传参的处理等。
步骤
1.初始化
ArrayList<ArrayList<String>> columns = new ArrayList<ArrayList<String>>();
BufferedReader br = null;
String sCurrentLine;
BufferedReader in = new BufferedReader(new FileReader("read_test.csv"));
2.读取表格的第一行
// 读取表格第一行作为map中的key
String key = in.readLine();
List<String> keyList = Arrays.stream(key.split(","))
.filter(Objects::nonNull)
.filter(string -> !string.isEmpty())
.collect(Collectors.toList());
按行读取是readLIne(), 这里采用了流式编程Arrays.stream(key.split(",")).collect(Collectors.toList())将以逗号分隔的数据变成list类型,其中.filter(Objects::nonNull)滤除表格中为null的值,.filter(string -> !string.isEmpty())滤除空值。便于后边数据长度的比较。
3.从第二行开始读取数据作为value
String s = null;
int line = 1;
while ((s = in.readLine()) != null) {