GroupingBy Exercise

Run Settings
LanguageJava
Language Version
Run Command
import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.Arrays; import java.util.stream.Collectors; class Main { public static void main(String[] args) { List<Item> items = Arrays.asList( new Item("Mouse", 15.0), new Item("Keyboard", 25.0), new Item("Mouse", 30.0), new Item("Keyboard", 120.0), new Item("Mouse", 10.0) ); Map<String, Integer> itemsCountByName = items.stream() .map(Item::getName) .collect(Collectors.groupingBy(name -> name, TreeMap::new, Collectors.summingInt(n -> 1))); itemsCountByName.forEach((k,v) -> System.out.println(k + ": " + v)); Map<String, Double> averagePricePerProduct = items.stream() .collect(Collectors.groupingBy(Item::getName, TreeMap::new, Collectors.averagingDouble(Item::getPrice))); averagePricePerProduct.forEach((k,v) -> System.out.println(k + ": " + String.format("%.2f", v))); Map<String, Double> totalPerCategory = items.stream() .collect(Collectors.groupingBy(item -> getCategory(item.getPrice()), Collectors.summingDouble(Item::getPrice))); final String[] categories = {"Cheap", "Moderate", "Expensive"}; for(String category : categories) { System.out.println(category + ": " + String.format("%.2f", totalPerCategory.get(category))); } } private static String getCategory(double price) { if (price < 20) { return "Cheap"; } else if (price >= 20 && price <= 100) { return "Moderate"; } return "Expensive"; } }
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; } }
Editor Settings
Theme
Key bindings
Full width
Lines