I have a following list of teams with their score:
List<String> teams = Arrays.asList("Dortmund 8", "Bayern 10", "Madrid 9", "Bayern 2", "Dortmund 4");
I need to output the team who got maximum score. If the scores are equal, output the team who got it first. In my example Dortmund and Bayern has equal score, but Bayern got it first. So the output is Bayern. Here is what I have for now:
Map<String, Integer> map = new HashMap<>();
for (String s : teams) {
String[] rec = s.split(" ");
int val = Integer.parseInt(rec[1]);
map.put(rec[0], map.get(rec[0])==null ? val : map.get(rec[0]) + val);
}
System.out.println(map);
The code just sum the scores of each team and save it on map. I could not change the way I need.
int max = 0;
String bestTeam="";
Map<String, Integer> map = new HashMap<>();
for (String s : teams)
{
String[] rec = s.split(" ");
int val = Integer.parseInt(rec[1]);
int sum = map.get(rec[0])==null ? val : map.get(rec[0]) + val;
map.put(rec[0], sum);
if (sum>max) {
max = sum;
bestTeam = rec[0];
}
}
System.out.println("Max score winner team :" + bestTeam + "-["+max+"] goals");
Other approaches just selected the max entry. The streams approaches written here by Alex Rudenko and Nikolas Charalambidis are the perfect example of how streams should handle this scenarios. Related to this, the use of a map, which solely is used to save the total scored goals for each team. The sorting is implicit in an arraylist iteration. The hashmap wasn't never involved in any type of sorting.
Dortmund 11", "Bayern 10", "Madrid 9", "Bayern 2", "Bayern 4"
The winner of this list is not Dortmund, but Bayern.
The best team is the one which scores the most goals, after adding all the entries. If two teams share the same max score, the winner is the team that first reach to that max.
Dortmund 15", "Bayern 2", "Dortmund 4", "Bayern 20", "Dortmund 3"
Both teams share the same max score: 22. The winner is Bayern, as it reached the max score first.
The logic is as simple as comparing the current maximum score with the current sum. The condition is sum>max and not sum>=max to guarantee that the first team who reached to that max is the winner.
Tested, working:
Max score winner team :Bayern-[12]

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With