![](/img/trans.png)
[英]How to stream a csv file with header to a HashMap<String, Double> in Java?
[英]convert a csv file of header and lines to an array of hashmap using java streams
我如何使用Java流將頭和行的csv文件轉換為hashmap數組? 例如。
orderNo, totals, charges, taxes, payments
ord121,1500.00,30.00,25.00,Paid
ord8925,1700.00,130.00,75.00,Paid
ord7115,300.00,130.00,75.00,Paid
Hashmap的數組[0]的名稱應為orderNo,值應為ord121
Hashmap的Array [1]的名稱應為orderNo,值應為ord8925 ...等
嘗試過此方法,但停留在如何使行(0)內容作為哈希圖名稱
公共靜態無效readFileToMap(){
Pattern pattern = Pattern.compile(",");
String csvFile = inputDirPreFix + "input/file2.tsv";
try (BufferedReader in = new BufferedReader(new FileReader(csvFile));){
Map<String,String> namefreq = in
.lines()
.skip(1)
.map(lineData -> pattern.split(lineData))
.collect(HashMap::new, (map, lineData) ->
map.put(lineData[0], lineData[1]),
Map::putAll);
namefreq.forEach((k, v) -> System.out.println(k + " => " + v));
}
catch (Exception ex) {
Logger.getLogger("FileProcessing").log(Level.SEVERE, null, ex);
}
}
我認為您應該將每一行都轉換為Map<String, String>
,然后將所有地圖收集到List<Map<String, String>>
:
try (BufferedReader in = new BufferedReader(new FileReader(csvFile))) {
List<Map<String,String>> namefreq = in.lines()
.skip(1)
.map(line -> pattern.split(line)) // or pattern::split
.map(line -> {
Map<String, String> map = new HashMap<>();
map.put("NAME_OF_FIRST_COLUMN", line[0]);
map.put("NAME_OF_SECOND_COLUMN", line[1]);
// ... (etc)
return map;
})
.collect(Collectors.toList());
}
編輯:最好不要收集到地圖列表,而最好創建自己的類,即Order
,其中具有orderNo
, totals
等屬性,還有getter和setter以及接收整行的構造函數,或者也許每一個屬性。 然后,您可以收集到List<Order>
。
暫時沒有流管理...
public static void readFileToMap() {
String csvFile = inputDirPreFix + "input/file2.tsv";
String [] strArrHeaderFields =new String [20] ;
HashMap objDataHashMap ;
HashMap <Integer,Object> objAggregateData = new HashMap(); ;
String [] strArrValues = new String[20];
try {
List<String> fileLinesList = Files.readAllLines(Paths.get(csvFile));
strArrHeaderFields =fileLinesList.get(0).split(",");
//System.out.println( Arrays.toString(objHeaderFields) );
//skip header line and collect data lines in hashmap with Name as Header line values..
// for every data line,
for( int i=1; i< fileLinesList.size(); i ++) {
objDataHashMap = new HashMap();
//get values from each data line
strArrValues =fileLinesList.get(i).split(",");
for( int j=0; j< strArrHeaderFields.length; j++) {
objDataHashMap.put(strArrHeaderFields[j], strArrValues[j]);
}
//System.out.println( "objDataHashMap Count of Records ...." + objDataHashMap.size() );
objAggregateData.put(i,objDataHashMap);
}
System.out.println( "objAggregateData Count of Records ...." + objAggregateData.size() );
objAggregateData.forEach((k,v) -> {
System.out.println(k + " : " + v );
});
} catch (Exception ex) {
Logger.getLogger("FileProcessing").log(Level.SEVERE, null, ex);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.