我有一个这样的 csv 数据集:
A, 10, USA
B,30, UK
C,4,IT
A,20,UK
B,10,USA
我想阅读这个 csv 行并提供以下输出:
A has ran 30 miles with average of 15.
B has ran 30 miles with average of 20.
C has ran 4 miles with average of 4.
我想在 Java 中实现这一点。我在 C# 中使用 Linq 完成了此操作:
var readlines = File.ReadAllLines(filename);
var query = from lines in readlines
let data = lines.Split(',')
select new
{
Name = data[0],
Miles = data[1],
};
var values = query.GroupBy(x => new {x.Name}).Select(group => new { Person = group.Key, Events = group.Sum(g =>Convert.ToDouble(g.Miles)) ,Count = group.Count() });
我希望在 Java 中执行此操作,但我不确定是否可以在不使用任何第三方库的情况下执行此操作?有任何想法吗?到目前为止,我的 Java 代码如下所示:
CSVReader reader = new CSVReader(new FileReader(filename));
java.util.List<String[]> content = reader.readAll();
String[] row = null;
for(Object object:content)
{
row = (String[]) object;
String Name = row[0];
String Miles = row[1];
System.out.printf("%s has ran %s miles %n",Name,Miles);
}
reader.close();
}
我正在寻找一种很好的方法来获取每个名称的总里程值以计算平均值。