我有這個 CSV 檔案:
id,name,mark
20203923380,Lisa Hatfield,62
20200705173,Jessica Johnson,59
20205415333,Adam Harper,41
20203326467,Logan Nolan,77
我正在嘗試使用以下代碼處理它:
try (Stream<String> stream = Files.lines(Paths.get(String.valueOf(csvPath)))) {
DoubleSummaryStatistics statistics = stream
.map(s -> s.split(",")[index]).skip(1)
.mapToDouble(Double::valueOf)
.summaryStatistics();
} catch (IOException e) // more code
我想按其名稱獲取列。
我想我需要將索引驗證為用戶作為整數輸入的列的索引,如下所示:
int index = Arrays.stream(stream).indexOf(columnNS);
但它不起作用。
該流應該具有以下值,例如:
柱子:"mark"
62、59、41、77
uj5u.com熱心網友回復:
我需要驗證索引是用戶作為整數輸入的列的索引......但它不起作用。
Arrays.stream(stream).indexOf(columnNS)
Stream IPA中沒有方法indexOf。我不確定你的意思是什么,stream(stream)但這種方法是錯誤的。
為了獲得有效的索引,您需要列的名稱。并且基于name,您必須分析從檔案中檢索到的第一行。就像在列名為“mark”的示例中一樣,您需要找出該名稱是否存在于第一行以及它的索引是什么。
我想要的是通過它的名稱來獲取列......應該是流......
流旨在成為有狀態的。它們是在 Java 中引入的,目的是提供富有表現力和清晰的代碼結構方式。即使你設法將有狀態的條件邏輯塞進一個流中,你也會失去這個優勢并最終得到比普通回圈更不清晰的復雜代碼(剩余:迭代解決方案幾乎總是表現更好)。
所以你想保持你的代碼干凈,你可以選擇:使用迭代方法解決這個問題,或者放棄在流中動態確定列索引的要求。
這就是您如何使用回圈根據列名動態讀取檔案資料的任務:
public static List<String> readFile(Path path, String columnName) {
List<String> result = new ArrayList<>();
try(var reader = Files.newBufferedReader(path)) {
int index = -1;
String line;
while ((line = reader.readLine()) != null) {
String[] arr = line.split("\\p{Punct}");
if (index == -1) {
index = getIndex(arr, columnName);
continue; // skipping the first line
}
result.add(arr[index]);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
// validation logic resides here
public static int getIndex(String[] arr, String columnName) {
int index = Arrays.asList(arr).indexOf(columnName);
if (index == -1) {
throw new IllegalArgumentException("Given column name '" columnName "' wasn't found");
}
return index;
}
// extracting statistics from the file data
public static DoubleSummaryStatistics getStat(List<String> list) {
return list.stream()
.mapToDouble(Double::valueOf)
.summaryStatistics();
}
public static void main(String[] args) {
DoubleSummaryStatistics stat = getStat(readFile(Path.of("test.txt"), "mark"));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/464546.html
上一篇:python讀取csv錯誤
