[英]Java: convert List<List<String>> into List<List<Double>>
I have a List-List from a Filereader (String), how can I convert it into a List-List (Double): I have to return a List of the first Values of the line-Array.我有一个来自 Filereader (String) 的 List-List,如何将其转换为 List-List (Double):我必须返回一个包含 line-Array 的第一个 Values 的 List。 Thanks.谢谢。
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;
you can use below method to convert all the list of String to Double您可以使用以下方法将所有字符串列表转换为 Double
public static <T, U> List<U> convertStringListTodoubleList(List<T> listOfString, Function<T, U> function)
{
return listOfString.stream()
.map(function)
.collect(Collectors.toList());
}
Calling Method调用方式
List<Double> listOfDouble = convertStringListTodoubleList(listOfString,Double::parseDouble);
The java.util.stream.Collectors have a handy method for this. java.util.stream.Collectors 有一个方便的方法。 Please refer to the below code snippet.请参考下面的代码片段。 You can replace with your logic你可以用你的逻辑替换
Map<String, Integer> map = list.stream().collect(
Collectors.toMap(kv -> kv.getKey(), kv -> kv.getValue()));
I'm not sure what you are trying to get as output exactly, but it's not that complicated in any case.我不确定你想得到什么作为输出,但无论如何都没有那么复杂。 Assuming you have something like this:假设你有这样的事情:
[["1", "2"],
["3", "4"]]
If you want to get all the first elements as Double [1, 3]
(Assuming the first element is always present):如果要将所有第一个元素都设为 Double [1, 3]
(假设第一个元素始终存在):
List<Double> firstAsDouble = allLines.stream()
.map(line -> line.get(0))
.map(Double::parseDouble)
.collect(Collectors.toList());
If instead you just want to convert all String values to Double and keep the structure the same:如果您只想将所有 String 值转换为 Double 并保持结构不变:
List<List<Double>> matrix = allLines.stream()
.map(line -> line.stream().map(Double::parseDouble).collect(Collectors.toList()))
.collect(Collectors.toList());
Or if you'd like to output a single array with all values ( [1, 2, 3, 4]
), you can flatMap it:或者,如果您想输出包含所有值( [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.