Guest User

Untitled

a guest
Jul 29th, 2019
127
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.*;
  2. import java.util.stream.Collectors;
  3.  
  4. import static java.util.Map.Entry.comparingByValue;
  5. import static java.util.stream.Collectors.toMap;
  6.  
  7. public class feedTheAnimals {
  8. public static void main(String[] args) {
  9. Scanner sc = new Scanner (System.in);
  10. String input = sc.nextLine();
  11. Map<String,Integer> animalsFoodLimit = new TreeMap<>();
  12. Map<String,Integer> hungryAnimalAreas = new TreeMap<>();
  13.  
  14. while (!input.equals("Last Info")) {
  15. String[] tokens = input.split(":");
  16. String command = tokens[0];
  17. String name = tokens[1];
  18. String area = tokens[3];
  19. if (command.equals("Add")) {
  20. if (!animalsFoodLimit.containsKey(name)) {
  21. animalsFoodLimit.put(name, Integer.parseInt(tokens[2]));
  22. if (!hungryAnimalAreas.containsKey(area)) {
  23. hungryAnimalAreas.put(area, 0);
  24. }
  25. hungryAnimalAreas.put(area, hungryAnimalAreas.get(area)+1);
  26. } else {
  27. animalsFoodLimit.put(name, animalsFoodLimit.get(name) + Integer.parseInt(tokens[2]));
  28. }
  29. } else if (command.equals("Feed")) {
  30. if (animalsFoodLimit.containsKey(name)) {
  31. animalsFoodLimit.put(name, animalsFoodLimit.get(name) - Integer.parseInt(tokens[2]));
  32. if (animalsFoodLimit.get(name) <= 0) {
  33. animalsFoodLimit.remove(name);
  34. System.out.printf("%s was successfully fed%n",name);
  35. if (hungryAnimalAreas.get(area) == 1) {
  36. hungryAnimalAreas.remove(area);
  37. } else {
  38. hungryAnimalAreas.put(area, hungryAnimalAreas.get(area) -1);
  39. }
  40. }
  41. }
  42. }
  43. input = sc.nextLine();
  44. }
  45. Map<String, Integer> reverseSortedMap = animalsFoodLimit
  46. .entrySet()
  47. .stream()
  48. .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
  49. .collect(
  50. toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
  51. LinkedHashMap::new));
  52. System.out.println("Animals:");
  53. for (var entry: reverseSortedMap.entrySet()) {
  54. System.out.println(entry.getKey()+" -> "+entry.getValue()+"g");
  55. }
  56. Map<String, Integer> reverseSortedArea = hungryAnimalAreas
  57. .entrySet()
  58. .stream()
  59. .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
  60. .collect(
  61. toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
  62. LinkedHashMap::new));
  63. System.out.println("Areas with hungry animals:");
  64. for (var entry: reverseSortedArea.entrySet()) {
  65. if (entry.getValue() != 0) {
  66. System.out.println(entry.getKey() + " : " + entry.getValue());
  67. }
  68. }
  69. }
  70. }
RAW Paste Data