![](/img/trans.png)
[英]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.