简体   繁体   English

如何从枚举的 ArrayList 中获取总值

[英]How to get a total value from an ArrayList of enums

I've have an ArrayList<Herbs> which stores these enum s below我有一个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;
    }
}

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?我怎样才能在这个 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.这是我在 Java 的第二周。 My goal is to get a total value of points from herbs , something like reduce() method in JavaScript.我的目标是从herbs中获得总分值,例如 JavaScript 中的reduce()方法。

my goal is to get a total value of points from herbs, something like reduce() method in JavaScript .我的目标是从草药中获得总分值,例如JavaScript中的reduce()方法。

In Java, we have a notion of Stream - which basically a mean of iteration over a source of data, which could be a collection, array, string, etc. I suggest you to have a look this tutorial created by Oracle .在 Java 中,我们有一个Stream的概念——它基本上是对数据源的迭代的平均值,可以是集合、数组、字符串等。我建议你看看这个由 Z30164ZED78B6C40F73 创建的教程Since your background is JavaScript, your prior knowledge might be a support in exploring streams.由于您的背景是 JavaScript,因此您的先验知识可能对探索流有帮助。 I guess some operations offered by Stream API like map , reduce , forEach would look vaguely familiar to you.我猜 Stream API 提供的一些操作,比如mapreduceforEach对你来说看起来有点熟悉。

But keep in mind that streams doesn't act like plain loops.但请记住,的行为不像普通的循环。 Hence, under the hood, Stream.map() is not doing precisely the same thing as Array.map() in JavaScript.因此,在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. 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. And we also have several specialized reduction forms like max() , count() , sum() .而且我们还有几个专门的归约 forms 像max()count()sum()

sum() - as its name suggests, produces the total sum of elements, and can be used in a primitive stream . sum() - 顾名思义,产生元素的总和,可用于原始 stream You can do the same thing using reduce() , but it would make your code more verbose and less expressive.您可以使用reduce()做同样的事情,但它会使您的代码更冗长且缺乏表现力。

Implementation执行

You can extract the points from each Herbs member by applying mapToInt() which returns an IntStream ( primitive stream of int -valued elements ), and then apply sum() to obtain the total.您可以通过应用mapToInt()从每个Herbs成员中提取点,它返回一个IntStreamint值元素的原始 stream ),然后应用sum()以获得总数。

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.如果 class 的实例旨在表示单个 object,则单数名词更适合其名称。 For example, Month and DayOfWeek enum-classes from the java.time package.例如, java.time package 中的MonthDayOfWeek枚举类。

here is an example: https://www.online-java.com/Qy3C2igd0t这是一个例子: 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's Sum collector is the shortest way: Stream 的 Sum 收集器是最短的方法:

int sum = herbs.stream().collect(Collectors.summingInt(Herbs::getPoints));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM