我有一个 ArrayList(Result),其中 Result 对象都包含对 Event 对象的引用。 ArrayList 中可能有 50 个 Result 对象,但只有 5 个不同的 Event 对象。有没有办法遍历 ArrayList 并将具有相同 Event.getName() 引用的结果组合在一起?
我想在“跳高”事件的结果上单独运行一个方法,然后只在“跳远”事件的结果上运行,等等。 我不会事先知道我的结果列表包含哪些事件,因为它们是根据用户输入创建的。
我知道如何根据事件名称对 ArrayList 进行排序,但我想按事件拆分列表并将它们存储在其他临时列表中(?)
来自结果类:
public Result(double result, int attemptNumber, Participant participant, Event event) {
this.result = result;
this.attemptNumber = attemptNumber;
this.participant = participant;
this.event = event;
}
来自事件类:
public Event (String eventName, int attemptsAllowed) {
this.eventName = eventName;
this.attemptsAllowed = attemptsAllowed;
}
public String getEventName() {
return eventName;
}
结果对象未排序地存储在名为 allResults 的 ArrayList 中,这是第三类中的一个方法,它根据输入的事件名称对 allResults 的副本(称为 resultByEvent)进行排序和修整,并仅保留每个参与者的最高结果:
public ArrayList<Result> resultsByEvent(String eventName) {
resultsByEvent.addAll(allResults);
for(int i = 0; i < resultsByEvent.size(); i++) {
Event event = resultsByEvent.get(i).getEvent();
if(!event.getEventName().equals(eventName)) {
resultsByEvent.remove(i);
}
}
Collections.sort(resultsByEvent, new EventLeaderboard());
for(int n = 0; n < resultsByEvent.size(); n++) {
for(int j = n + 1; j < resultsByEvent.size(); j++) {
Participant participant1 = resultsByEvent.get(n).getParticipant();
Participant participant2 = resultsByEvent.get(j).getParticipant();
if(participant1.getParticipantId() == participant2.getParticipantId()) {
resultsByEvent.remove(j);
j = j - 1;
}
}
}
return resultsByEvent;
}
以上是我要在原始结果列表中的所有事件上运行的内容。
最佳答案
您可以使用 Stream
API 执行此操作:
按名称对事件进行分组
Map<String, List<Event>> eventsGroupedByName = allResults.stream().collect(
Collectors.groupingBy(e -> e.getEvent().getName()));
按事件名称对结果进行分组
Map<String, List<Result>> resultsGroupedByEventName = allResults.stream().collect(
Collectors.groupingBy(r -> r.getEvent().getName()));
关于java - 对复合对象列表进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41895500/