Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.util.stream.Collectors;
- import static java.util.Map.Entry.comparingByValue;
- import static java.util.stream.Collectors.toMap;
- public class feedTheAnimals {
- public static void main(String[] args) {
- Scanner sc = new Scanner (System.in);
- String input = sc.nextLine();
- Map<String,Integer> animalsFoodLimit = new TreeMap<>();
- Map<String,Integer> hungryAnimalAreas = new TreeMap<>();
- while (!input.equals("Last Info")) {
- String[] tokens = input.split(":");
- String command = tokens[0];
- String name = tokens[1];
- String area = tokens[3];
- if (command.equals("Add")) {
- if (!animalsFoodLimit.containsKey(name)) {
- animalsFoodLimit.put(name, Integer.parseInt(tokens[2]));
- if (!hungryAnimalAreas.containsKey(area)) {
- hungryAnimalAreas.put(area, 0);
- }
- hungryAnimalAreas.put(area, hungryAnimalAreas.get(area)+1);
- } else {
- animalsFoodLimit.put(name, animalsFoodLimit.get(name) + Integer.parseInt(tokens[2]));
- }
- } else if (command.equals("Feed")) {
- if (animalsFoodLimit.containsKey(name)) {
- animalsFoodLimit.put(name, animalsFoodLimit.get(name) - Integer.parseInt(tokens[2]));
- if (animalsFoodLimit.get(name) <= 0) {
- animalsFoodLimit.remove(name);
- System.out.printf("%s was successfully fed%n",name);
- if (hungryAnimalAreas.get(area) == 1) {
- hungryAnimalAreas.remove(area);
- } else {
- hungryAnimalAreas.put(area, hungryAnimalAreas.get(area) -1);
- }
- }
- }
- }
- input = sc.nextLine();
- }
- Map<String, Integer> reverseSortedMap = animalsFoodLimit
- .entrySet()
- .stream()
- .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
- .collect(
- toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
- LinkedHashMap::new));
- System.out.println("Animals:");
- for (var entry: reverseSortedMap.entrySet()) {
- System.out.println(entry.getKey()+" -> "+entry.getValue()+"g");
- }
- Map<String, Integer> reverseSortedArea = hungryAnimalAreas
- .entrySet()
- .stream()
- .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
- .collect(
- toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
- LinkedHashMap::new));
- System.out.println("Areas with hungry animals:");
- for (var entry: reverseSortedArea.entrySet()) {
- if (entry.getValue() != 0) {
- System.out.println(entry.getKey() + " : " + entry.getValue());
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement