英文:
How to get average in Java
问题
如何在Java中使用函数式编程获取平均值?
这是我尝试过的...
似乎在`IntStream.of`这里有问题
我想从数组的特定行中获取平均值
public static void average(List<List<String>> rows){
IntStream stream = rows.stream()
.mapToInt(row -> Integer.parseInt(row.get(2)));
OptionalDouble obj = stream.average();
if (obj.isPresent()) {
System.out.println(obj.getAsDouble());
}
else {
System.out.println("-1");
}
}
rows是从Excel文件中读取的行数组。
英文:
How to get average using functional programming in java?
This is what I tried ...
It seems like its not working at IntStream.of
I would like to get average from a specific row of the array
public static void average(List<List<String>> rows){
IntStream stream = IntStream.of(e -> Integer.parseInt(e.get(2)));
OptionalDouble obj = stream.average();
if (obj.isPresent()) {
System.out.println(obj.getAsDouble());
}
else {
System.out.println("-1");
}
}
rows is the array are rows read from an excel file.
答案1
得分: 2
Stream.of(elem1, elem2)使用给定的元素创建一个流。
想象你有一个盒子里面有100张照片。
如果你使用 Stream.of(box),你会得到一个包含__盒子__的流,返回1个盒子。
而你想要的是一串__照片__。为了得到这个,你应该使用 box.stream(),而不是 Stream.of(box)。
然后你接下来的问题是,你似乎不太理解reduce的作用。你需要告诉系统如何将两个结果整合在一起,而不仅仅是如何得到一个结果。
你在这里想要的不是首先进行reduce操作,而是想要将给定的'foto'(在你的情况下是一个字符串列表)映射到一个整数,这不仅需要使用 e.get(),还需要使用Integer.parseInt,而且你需要使用map,而不是reduce。
英文:
Stream.of(elem1, elem2) creates a stream with the stated elements.
Imagine you have a box with 100 fotos in it.
If you do Stream.of(box), you get a stream of boxes, returning 1 box.
What you wanted was a stream of fotos. To get that, you want box.stream(), not Stream.of(box).
Your next problem then is that you don't seem to understand what reduce does. You need to tell the system how to integrate two results, not just how to get a result.
What you want here isn't reducing in the first place, you want to map a given 'foto' (a List of string in your case) to an integer, which requires not just e.get(), but also an Integer.parseInt, and you want map, not reduce.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论