我有一个来自Filereader (String)的List-List,如何将其转换为List-List (Double):我必须返回line-Array的第一个值的列表。谢谢。
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;发布于 2019-12-04 18:58:51
您可以使用下面的方法将所有字符串列表转换为双精度
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);发布于 2019-12-04 19:53:27
为此,java.util.stream.Collectors提供了一种方便方法。请参考下面的代码片段。你可以用你的逻辑替换
Map<String, Integer> map = list.stream().collect(
Collectors.toMap(kv -> kv.getKey(), kv -> kv.getValue())); 发布于 2019-12-04 23:36:11
我不确定你到底想要得到什么作为输出,但这在任何情况下都不是那么复杂。假设你有这样的东西:
[["1", "2"],
["3", "4"]]如果您想以双倍[1, 3]的形式获取所有第一个元素(假设第一个元素始终存在):
List<Double> firstAsDouble = allLines.stream()
.map(line -> line.get(0))
.map(Double::parseDouble)
.collect(Collectors.toList());相反,如果您只想将所有字符串值转换为双精度,并保持结构不变:
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());https://stackoverflow.com/questions/59174133
复制相似问题