Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package set_and_Map_CodingTasks_1;
- import java.util.*;
- public class newSolution {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- Map<String, Item> inventory = new HashMap<>();
- String input = "";
- while (!"end".equals(input = scanner.nextLine())) {
- String[] parameters = input.split(" ");
- String command = parameters[0];
- StringBuilder output = new StringBuilder();
- output.append("Ok: ");
- if (command.equals("add")) {
- String itemName = parameters[1];
- double itemPrice = Double.parseDouble(parameters[2]);
- String itemType = parameters[3];
- if (inventory.containsKey(itemName)) {
- System.out.printf("Error: Item %s already exists%n", itemName);
- } else {
- Item item = new Item(itemName, itemPrice, itemType);
- inventory.put(itemName, item);
- System.out.printf("Ok: Item %s added successfully%n", itemName);
- }
- continue;
- } else if (command.equals("filter")) {
- String filtrationType = parameters[2];
- if (filtrationType.equals("price")) {
- String priceType = parameters[3];
- if (priceType.equals("to")) {
- double maxPrice = Double.parseDouble(parameters[4]);
- inventory.entrySet().stream()
- .sorted(Comparator.comparing((e1) -> e1.getValue().price))
- .filter(e -> e.getValue().price <= maxPrice)
- .limit(10)
- .forEach(e -> output.append(String.format("%s, ", e.getValue().asString())));
- } else if (priceType.equals("from")) {
- double minValue = Double.parseDouble(parameters[4]);
- inventory.entrySet().stream()
- .sorted(Comparator.comparing((e1) -> e1.getValue().price))
- .filter(parameters.length == 5 ? e -> e.getValue().price >= minValue : e -> e.getValue().price >= minValue && e.getValue().price <= Double.parseDouble(parameters[6]))
- .limit(10)
- .forEach(e -> output.append(String.format("%s, ", e.getValue().asString())));
- }
- } else if (filtrationType.equals("type")) {
- String typeToFilter = parameters[3];
- if (inventory.values().stream().noneMatch(item -> item.type.equals(typeToFilter))) {
- System.out.printf("Error: Type %s does not exist%n", typeToFilter);
- continue;
- }
- inventory.entrySet().stream()
- .sorted(Comparator.comparing((e1) -> e1.getValue().price))
- .filter(e -> e.getValue().type.equals(typeToFilter))
- .limit(10)
- .forEach(e -> output.append(String.format("%s, ", e.getValue().asString())));
- }
- }
- if (output.length() == 4) {
- System.out.println("Ok: ");
- } else {
- System.out.println(output.substring(0, output.length() - 2));
- }
- }
- }
- }
- class Item {
- String name;
- double price;
- String type;
- public Item(String name, double price, String type) {
- this.name = name;
- this.price = price;
- this.type = type;
- }
- public String asString() {
- return String.format("%s(%.2f)", name, price);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement