[英]How to get the total value from an ArrayList where one is product and the other one is price?
[英]How to get a total value from an ArrayList of enums
我有一个ArrayList<Herbs>
将这些enum
存储在下面
public enum Herbs{
OLD_SPICE(20),
PURPLE_LOTUS(50);
private final int points;
Herbs(int points) {
this.points = points;
}
public int getPoints() {
return points;
}
}
和我的数组列表
herbs = new ArrayList<>(Arrays.asList(Herbs.OLD_SPICE, Herbs.PURPLE_LOTUS));
我怎样才能在这个 ArrayList 中收集这个枚举的点值? 到目前为止,我已经尝试过了,但真的无法让它发挥作用。
public int getTotalPoints(ArrayList<Herbs> herbs) {
ArrayList<Herbs> enumValues = Arrays.asList(herbs.values());
}
这是我在 Java 的第二周。 我的目标是从herbs
中获得总分值,例如 JavaScript 中的reduce()
方法。
我的目标是从草药中获得总分值,例如JavaScript中的
reduce()
方法。
在 Java 中,我们有一个Stream的概念——它基本上是对数据源的迭代的平均值,可以是集合、数组、字符串等。我建议你看看这个由 Z30164ZED78B6C40F73 创建的教程由于您的背景是 JavaScript,因此您的先验知识可能对探索流有帮助。 我猜 Stream API 提供的一些操作,比如map
, reduce
, forEach
对你来说看起来有点熟悉。
但请记住,流的行为不像普通的循环。 因此,在Stream.map()
Array.map()
的事情并不完全相同。
There are two general forms of reduction in the Stream API represented by the collect()
, which is used for mutable reduction, and reduce()
, which is meant to perform fold operation on a stream. 而且我们还有几个专门的归约 forms 像max()
, count()
, sum()
。
sum()
- 顾名思义,产生元素的总和,可用于原始 stream 。 您可以使用reduce()
做同样的事情,但它会使您的代码更冗长且缺乏表现力。
您可以通过应用mapToInt()
从每个Herbs
成员中提取点,它返回一个IntStream
( int
值元素的原始 stream ),然后应用sum()
以获得总数。
int totalPoints = herbs.stream()
.mapToInt(Herbs::getPoints)
.sum();
旁注:通常,类的名称(并且是一种特殊形式的类)是单数的。 如果 class 的实例旨在表示单个 object,则单数名词更适合其名称。 例如, java.time
package 中的Month
和DayOfWeek
枚举类。
这是一个例子: https://www.online-java.com/Qy3C2igd0t
var herbs = new ArrayList<>(Arrays.asList(Herbs.OLD_SPICE, Herbs.PURPLE_LOTUS));
System.out.println(herbs.stream().map(x -> x.getPoints()).reduce(0, Integer::sum));
Stream 的 Sum 收集器是最短的方法:
int sum = herbs.stream().collect(Collectors.summingInt(Herbs::getPoints));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.