[英]Java: convert List<List<String>> into List<List<Double>>
我有一個來自 Filereader (String) 的 List-List,如何將其轉換為 List-List (Double):我必須返回一個包含 line-Array 的第一個 Values 的 List。 謝謝。
private List<List<String>> stoxxFileReader(String file, int column) throws IOException {
List<List<String>> allLines = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
br.readLine();
String line = null;
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
allLines.add(Arrays.asList(values));
}
}
return allLines;
您可以使用以下方法將所有字符串列表轉換為 Double
public static <T, U> List<U> convertStringListTodoubleList(List<T> listOfString, Function<T, U> function)
{
return listOfString.stream()
.map(function)
.collect(Collectors.toList());
}
調用方式
List<Double> listOfDouble = convertStringListTodoubleList(listOfString,Double::parseDouble);
java.util.stream.Collectors 有一個方便的方法。 請參考下面的代碼片段。 你可以用你的邏輯替換
Map<String, Integer> map = list.stream().collect(
Collectors.toMap(kv -> kv.getKey(), kv -> kv.getValue()));
我不確定你想得到什么作為輸出,但無論如何都沒有那么復雜。 假設你有這樣的事情:
[["1", "2"],
["3", "4"]]
如果要將所有第一個元素都設為 Double [1, 3]
(假設第一個元素始終存在):
List<Double> firstAsDouble = allLines.stream()
.map(line -> line.get(0))
.map(Double::parseDouble)
.collect(Collectors.toList());
如果您只想將所有 String 值轉換為 Double 並保持結構不變:
List<List<Double>> matrix = allLines.stream()
.map(line -> line.stream().map(Double::parseDouble).collect(Collectors.toList()))
.collect(Collectors.toList());
或者,如果您想輸出包含所有值( [1, 2, 3, 4]
)的單個數組,您可以對其進行 flatMap:
List<Double> flatArray = allLines.stream()
.flatMap(line -> line.stream().map(Double::parseDouble))
.collect(Collectors.toList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.