Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get a total value from an ArrayList of enums

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading