gpt4 book ai didi

java - 使用 'Collections.frequency' 获取给定一个值的实例计数

转载 作者:行者123 更新时间:2023-12-01 16:53:09 24 4
gpt4 key购买 nike

为了简化我正在做的事情,让我们使用 learnfromexamples.com 中的示例我修改了一些位。

package test;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


class Employee {
private String empno;
private String empName;

public Employee(String empno, String empName ) {
this.empno = empno;
this.empName = empName;
}

public String getEmpno() {
return empno;
}

public void setEmpno(String empno) {
this.empno = empno;
}

public String getEmpName() {
return empName;
}

public void setEmpName(String empName) {
this.empName = empName;
}
@Override
public String toString() {
return "Empno is "+ empno + " Empname is " + empName;
}
public Employee() {
// TODO Auto-generated constructor stub
}

@Override
public boolean equals(Object arg0) {
// TODO Auto-generated method stub
boolean flag = false;
Employee employee = (Employee) arg0;
if(null!= employee && employee.getEmpName().equalsIgnoreCase(empName) && employee.getEmpno().equalsIgnoreCase(empno)){
flag = true;
}
return flag;
}

}


public class Test {
public static void main(String[] args) {

List<Employee> empList = new ArrayList<Employee>();
empList.add(new Employee("001", "Shidhar"));
empList.add(new Employee("002", "Pathy"));
empList.add(new Employee("003", "Sahana"));
empList.add(new Employee("003", "Sahana"));
empList.add(new Employee("004", "Sahana"));
empList.add(new Employee("003", "Sahana"));

//Get the occurrence of "new Employee("003", "Sahana")" from empLists
//int sahanaCount = Collections.frequency(empList, new Employee("003"));
//System.out.println("Count of sahana is : " +sahanaCount);

Set<Employee> uniqueId = new HashSet<Employee>(empList);
for (Employee emId : uniqueId) {
System.out.println("The emp with id "+emId.getEmpno()+" was repeated: "
+ Collections.frequency(empList, emId.getEmpName()));
}

}
}

是否可以使用Collections.Frequency来查找给定一个变量的频率,例如Collections.Frequency(empList,"Sahana"); 产生 4。

另一种选择是我可以使用 HashMap 来保持计数,但假设我对 Collections.Frequency 印象深刻,并尝试使用它。

最佳答案

不,考虑到您的 equals 实现,这是不可能的。在 Java-8 中,您可以使用 Stream API 代替 Collections.Frequency:

empList.stream().map(Employee::getEmpName).filter(emId.getEmpName()::equals).count();

关于java - 使用 'Collections.frequency' 获取给定一个值的实例计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36307984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com