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

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

问题描述

我试着用这段代码打印出列表中名字约翰"的频率(人类有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());

}
}

但是值是 0 而不是 2.这段代码有什么问题?

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

推荐答案

Collections#frequency 如果您想计算特定 Human object 出现在您的列表中.但是您想检查拥有特定姓名的人数,无论该姓名是否可能出现在多个对象中.流在这里派上用场:

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中Object字段的频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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