gpt4 book ai didi

java - 如何获取 Observablelist 中的所有唯一属性并统计唯一属性?

转载 作者:行者123 更新时间:2023-12-01 17:41:39 25 4
gpt4 key购买 nike

我有一个ObservalbeList<Appointment> appointments 。每个appointment有一个type属性是一个字符串,可以返回 typegetType()方法。理想情况下,如果约会列表包含“常规、审核、每周、每周”,则输出将是:

General: 1, 
Review: 1,
Weekly: 2

虽然我可以迭代列表,但我在跟踪唯一值和这些值的计数时遇到了困难。

有推荐的方法可以实现这个吗?以下是我目前拥有的。


public void clickMenuReportsItemNumberOfAppointmentsByType(ActionEvent event) throws IOException{

TextAreaOutput.clear();

AppointmentDOA appointmentDOA = new AppointmentDOA(DBConnection.getConnection());
ObservableList<Appointment> Appointments = appointmentDOA.findAll();

// get all the types
// check the number of times each type shows up
ObservableList<String> type = FXCollections.observableArrayList();

for(int i =0; i < Appointments.size(); i++){
Appointments.get(i).getType();
if(!type.contains(Appointments.get(i).getType())){
type.add(Appointments.get(i).getType());
}
}
}

最佳答案

尝试 Java 8 流 API:

ObservableList<Appointment> Appointments = appointmentDOA.findAll();

Map<String, Long> appointmentsMap = appointments.stream()
.collect(Collectors.groupingBy(Appointment::getType, Collectors.counting()));

您将获得一个 map ,其中约会类型(字符串)作为键,计数作为值。此外,我建议对约会类型使用 Java 枚举:

enum AppointmentType {General, Review, Weekly};

ObservableList<Appointment> Appointments = appointmentDOA.findAll();

Map<AppointmentType, Long> appointmentsMap = appointments.stream()
.collect(Collectors.groupingBy(Appointment::getType, Collectors.counting()));

关于java - 如何获取 Observablelist 中的所有唯一属性并统计唯一属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60343071/

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