import java.util.List;
import java.util.Map;
class Main {
public static void main(String[] args) {
List<Item> items = List.of(
new Item("Mouse", 15.0), // Cheap
new Item("Mouse", 25.0), // Moderate
new Item("Keyboard", 120.0), // Expensive
new Item("Mouse", 10.0) // Cheap
);
ItemProcessor processor = new ItemProcessorImpl();
Map<String, Integer> byCategory = processor.countItemsByCategory(items);
byCategory.forEach((k,v) -> System.out.println(k + ": " + v));
Map<String, Double> discounts = processor.calculateTotalDiscounts(items);
discounts.forEach((k,v) -> System.out.println(k + ": " + v));
Map<String, Integer> byName = processor.countItemsByName(items);
byName.forEach((k,v) -> System.out.println(k + ": " + v));
}
}
import java.util.List;
import java.util.Map;
public interface ItemProcessor {
Map<String, Integer> countItemsByCategory(List<Item> items);
Map<String, Double> calculateTotalDiscounts(List<Item> items);
Map<String, Integer> countItemsByName(List<Item> items);
}
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class ItemProcessorImpl implements ItemProcessor {
@Override
public Map<String, Integer> countItemsByCategory(List<Item> items) {
return items.stream()
.map(Item::getPrice)
.map(this::getCategory)
.collect(Collectors.groupingBy(category -> category, TreeMap::new, Collectors.summingInt(n -> 1)));
}
@Override
public Map<String, Double> calculateTotalDiscounts(List<Item> items){
return items.stream()
.map(Item::getPrice)
.collect(Collectors.groupingBy(price -> this.getCategory(price), TreeMap::new, Collectors.summingDouble(price -> price * this.getDiscount(price))));
}
@Override
public Map<String, Integer> countItemsByName(List<Item> items){
return items.stream()
.map(Item::getName)
.collect(Collectors.groupingBy(
name -> name,
TreeMap::new,
Collectors.summingInt(n -> 1)));
}
private String getCategory(double price) {
if (price < 20.0) {
return "Cheap";
} else if (price >= 20.0 && price <= 100.0) {
return "Moderate";
}
return "Expensive";
}
private double getDiscount(double price) {
if (price < 20.0) {
return 0.05;
} else if (price >= 20.0 && price <= 100.0) {
return 0.1;
}
return 0.15;
}
}
public class Item {
private String name;
private double price;
public Item(String name, double price) {
this.name = name;
this.price = price;
}
public String getName(){
return this.name;
}
public double getPrice() {
return this.price;
}
}