lots of exercises in java... from https://github.com/exercism/java

Tournament.java 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.regex.Pattern;
  4. class Tournament {
  5. private static Pattern separatorPattern = Pattern.compile(";");
  6. private static Pattern newlinePattern = Pattern.compile("\\n");
  7. private Map<String, TeamResult> results;
  8. Tournament() {
  9. results = new HashMap<>();
  10. }
  11. String printTable() {
  12. StringBuilder sb = new StringBuilder();
  13. sb.append(String.format("%-30s | %2s | %2s | %2s | %2s | %2s\n",
  14. "Team", "MP", "W", "D", "L", "P"));
  15. results.entrySet()
  16. .stream()
  17. .sorted(Tournament::comparator)
  18. .forEach(e -> sb.append(
  19. String.format("%-30s | %2d | %2d | %2d | %2d | %2d\n",
  20. e.getKey(), e.getValue().getPlayed(), e.getValue().getWins(), e.getValue().getDraws(),
  21. e.getValue().getLosses(), e.getValue().getPoints())));
  22. return sb.toString();
  23. }
  24. private static int comparator(Map.Entry<String, TeamResult> teamA, Map.Entry<String, TeamResult> teamB) {
  25. int compareByPoints = Integer.compare(teamB.getValue().getPoints(), teamA.getValue().getPoints());
  26. return compareByPoints == 0 ? teamA.getKey().compareTo(teamB.getKey()) : compareByPoints;
  27. }
  28. void applyResults(final String resultString) {
  29. String[] matches = newlinePattern.split(resultString);
  30. for (String matchString: matches) {
  31. String[] column = separatorPattern.split(matchString);
  32. final TeamResult home = results.getOrDefault(column[0], new TeamResult());
  33. final TeamResult away = results.getOrDefault(column[1], new TeamResult());
  34. final Result result = Result.valueOf(column[2].toUpperCase());
  35. switch (result) {
  36. case WIN:
  37. home.applyResult(Result.WIN);
  38. away.applyResult(Result.LOSS);
  39. break;
  40. case LOSS:
  41. home.applyResult(Result.LOSS);
  42. away.applyResult(Result.WIN);
  43. break;
  44. case DRAW:
  45. home.applyResult(Result.DRAW);
  46. away.applyResult(Result.DRAW);
  47. break;
  48. }
  49. results.put(column[0], home);
  50. results.put(column[1], away);
  51. }
  52. }
  53. }