I’ve have an ArrayList<Herbs> which stores these enums below
public enum Herbs{
OLD_SPICE(20),
PURPLE_LOTUS(50);
private final int points;
Herbs(int points) {
this.points = points;
}
public int getPoints() {
return points;
}
}
and my array list
herbs = new ArrayList<>(Arrays.asList(Herbs.OLD_SPICE, Herbs.PURPLE_LOTUS));
how can I can collects the point values of this enums in this ArrayList? So far I’ve tried to this but really couldn’t make it work.
public int getTotalPoints(ArrayList<Herbs> herbs) {
ArrayList<Herbs> enumValues = Arrays.asList(herbs.values());
}
This is my second week in Java so don’t judge :))) my goal is to get a total value of points from herbs , something like reduce() method in Javascript.
>Solution :
You can extract the points from each Herbs member by applying mapToInt() which returns IntStream, and then apply sum() to obtain the total.
int totalPoints = herbs.stream()
.mapToInt(Herbs::getPoints)
.sum();
Sidenote: usually, names of classes (and is a special form class) are singular. If an instance of a class is meant to represent a single object, a singular noun would be more suitable for its name. For example, Month and DayOfWeek enum-classes from the java.time package.