You can utilize Java 8+ 's collection utilities to find the max values.
Just parse each line into an object and place it in a list. You can now group by division, and for each division list, locate the max. You must make sure your Boxer
class implements Comparable
for Collection.max
to actually work.
import java.util.*;
import java.util.stream.Collectors;
public class BoxingScores {
public static void main(String[] args) {
BoxingCompetition competition = parseFile("/boxingcompetition.txt");
Map<String, List<Boxer>> grouped = competition.getBoxers().stream()
.collect(Collectors.groupingBy(Boxer::getDivision));
List<Boxer> topScores = grouped.entrySet().stream()
.map(Map.Entry::getValue)
.map(Collections::max)
.collect(Collectors.toList());
System.out.println(topScores);
}
private static BoxingCompetition parseFile(String filename) {
List<Boxer> boxers = new ArrayList<>();
Scanner scan = new Scanner(BoxingScores.class.getResourceAsStream(filename));
int competitions = scan.nextInt();
scan.nextLine();
System.out.printf("Competitions: %d%n", competitions);
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] tokens = line.split(",");
String name = tokens[0];
int score = Integer.parseInt(tokens[1]);
String division = tokens[2];
boxers.add(new Boxer(name, division, score));
}
scan.close();
return new BoxingCompetition(competitions, boxers);
}
private static class BoxingCompetition {
private int count;
private List<Boxer> boxers;
public BoxingCompetition(int count, List<Boxer> boxers) {
this.count = count;
this.boxers = boxers;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public List<Boxer> getBoxers() {
return boxers;
}
public void setBoxers(List<Boxer> boxers) {
this.boxers = boxers;
}
}
private static class Boxer implements Comparable<Boxer> {
private String name;
private String division;
private int score;
public Boxer(String name, String division, int score) {
this.name = name;
this.division = division;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public int compareTo(Boxer other) {
return this.score - other.score; // Descending
}
@Override
public String toString() {
return String.format("{ name: \"%s\", division: \"%s\", score: %d }", name, division, score);
}
}
}
Output
[
{ name: "Eva", division: "flyweight", score: 96 },
{ name: "Harry", division: "featherweight", score: 90 }
]