可以如下嘗試:
package com.grs.stackOverFlow.pack06;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Data{
private Double volume;
private Double weight;
public Data(String string, String string2) {
setVolumeString(string);
setWeightString(string2);
}
public Double getVolume() {
return volume;
}
public Double getWeight() {
return weight;
}
public void setVolumeString(String volumeStr){
this.volume=Double.valueOf(volumeStr);
}
public void setWeightString(String weightStr){
this.weight=Double.valueOf(weightStr);
}
}
public class FileSummary01 {
public static void main(String[] args) throws IOException {
List<String> lines = Files.readAllLines(Paths.get("src/com/grs/stackOverFlow/pack06/data.txt"));
List<Data> data=lines.stream()
.skip(1)
.map(t->
{ String [] a =t.split("\\s+");
System.out.printf("arr : %s %s %n",a[0],a[1]);
return new Data(a[0],a[1]);}).collect(Collectors.toList());
System.out.println("sum of volume : " + data.stream().mapToDouble(Data::getVolume).sum());
System.out.println("sum of weight : " + data.stream().mapToDouble(Data::getWeight).sum());
}
}
如果你有大數據你可以嘗試parallelStream而不是流。
但是,這可能不會提高您對Java 7讀取文件的速度。有關單線程與多線程實現的性能比較,請參閱http://stackoverflow.com/a/40597140/3867574 –
您的答案不正確。其實我想sum(Volumn)/ sum(Weight),而不是sum(v1/w1 + v2/w2 + ... vn/wn)。您提供的鏈接非常出色,因爲它顯示了讀取文件的不同方式。不管怎麼說,還是要謝謝你。 – user84592