简体   繁体   English

如何计算对象的ArrayList中枚举的频率

[英]How to count frequency of an enum in an ArrayList of object

As an example to my question... Say I have an ArrayList containing Car objects. 作为我的问题的一个例子...说我有一个包含Car对象的ArrayList A Car object is comprised of a Model and Colour Enum . Car对象由ModelColour Enum I want to count how many car models of type Audi are in the list, Audi is an ENUM 我想算一下有多少型号为奥迪的车型,奥迪是ENUM

I have an int variable called int Audi 我有一个名为int Audi的int变量

And I'm trying Audi=Collections.frequency(list, Model.AUDI); 我正在尝试Audi=Collections.frequency(list, Model.AUDI);

However it is not counting the frequency and Audi=0 然而,它不计算频率和Audi=0

Where am I going wrong and how can I count the frequency of an enum? 我哪里出错了,如何计算枚举的频率?

Your use of Collections.frequency is incorrect; 您对Collections.frequency使用不正确; you are looking in a list of Car s for a Model enum, so it's no surprise that the count is 0. 你正在查看一个Model枚举的Car列表,所以计数为0就不足为奇了。

If you're using Java 8, you can set up a Stream so that you can filter the contents and then count the remaining elements. 如果您使用的是Java 8,则可以设置Stream以便可以filter内容,然后count剩余的元素。 This assumes that Car has a getModel getter method. 这假设Car具有getModel getter方法。

long audi = list.stream().filter( c -> c.getModel() == Model.AUDI ).count();

Collections.frequency only works if the array is containing objects of the same Type as the object passed. Collections.frequency仅在数组包含与传递的对象具有相同Type的对象时才有效。 In this case, you have an array of type <Car> and are checking for an object of type Model (an instance of Car will never equal an enum Model). 在这种情况下,您有一个类型为<Car>的数组,并且正在检查Model类型的对象(Car的实例永远不会等于枚举模型)。

You will need to write your own loop to go through and perform the count (it should be easy). 你需要编写自己的循环来完成并执行计数(应该很容易)。

Another approach(java8 required) is to first groupBy(in your case groupBy self) which will return Map<Car, List<Car>> , passing Collectors.counting() will return Map 另一种方法(需要java8)是首先将groupBy(在你的情况下为groupBy self)返回Map<Car, List<Car>> ,传递Collectors.counting()将返回Map

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.google.common.collect.Lists;

//guava & pseudocode
List<Car> listOfCars = Lists.newArrayList(Car.AUDI, Car.BMW, Car.AUDI, Car.AUDI, Car.BMW);

listOfCars.stream()
        .collect(Collectors.groupingBy(
                Function.identity(), 
                Collectors.counting()));

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

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