繁体   English   中英

如何获取ArrayList中对象的字段的频率

[英]how to get frequency of Object's field in ArrayList

我尝试使用此代码在列表中打印出名称“ John”的频率(人类有2个字段: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。这段代码中哪个错?

如果您想计算某个特定Human 对象出现在列表中的Collections#frequency ,则使用Collections#frequency是合适的。 但是,您想要检查具有特定名称的人数,而不管该名称是否可能出现在多个对象中。 流在这里派上用场:

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.");

好吧, menu包含Human对象,而不是字符串,这大概是getName()返回的。 因此, Collections.frequency()将检查menu包含“ John”,但不包含-而是包含名称为“ John”的人类

暂无
暂无

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

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