如何获取ArrayList中对象的字段的频率 [英] how to get frequency of Object's field in ArrayList

查看:136
本文介绍了如何获取ArrayList中对象的字段的频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用此代码在列表中打印出名称约翰"的频率(人类有2个字段:姓名和年龄):

I try this code to print out the frequency of name "John"in the list(Human has 2 field: name and age):

package test;
import data.Boy;
import data.Human;
import java.util.*;
import java.lang.*;
class Test
{
public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    List<Human> menu = new ArrayList();
       menu.add(new Human("John",20));
       menu.add(new Human("Smith",19));
       menu.add(new Human("Alice",12));
       menu.add(new Human("John",18));
       System.out.println(Collections.frequency(menu, menu.get(0).getName());

}
}

但是值是2而不是2,这是什么错误?

But the value is 0 instead of 2.Which's wrong in this code?

推荐答案

Collections#frequency would be appropriate if you wanted to count how many times a particular Human object appeared in your list. But you want to check the count of humans having a particular name, regardless of whether that name might occur in more than one object. Streams come in handy here:

List<Human> matches = menu.stream()
                          .filter(h -> h.getName().equals(menu.get(0).getName()))
                          .collect(Collectors.toList());

int size = matches == null ? 0 : matches.size();
System.out.println("There are " + size + " humans which match.");

这篇关于如何获取ArrayList中对象的字段的频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆