Java-8 Get count with value in specific range

javaaddict :

I have List of Products and want to find count of products in specific cost range like, if productList is having 10 products with cost between 1-10, 50 between 11-100 and 100 between 101-1000, then it should return a map as follow,

"1-10": 10 "11-100": 50 "101:1000": 100

  class Product {
        long id;
        long cost;
        String name;
        //getters setters
    }  

I tried many things but did not work, List productList = getProducts();

productList.stream().collect(Collectors.toMap(//logic to get map));

Highly appreciate any help.

Code_Mode :

You can create a Function for range and use Collectors.groupingBy as below,

Map<String, Long> countByCost = productList.stream()
                .collect(Collectors.groupingBy(costRange, TreeMap::new, Collectors.counting()));

Function<Product, String> costRange = ele -> {
        if(ele.cost >= 1 && ele.cost < 11)
            return "1-10";
        if(ele.cost >= 11 && ele.cost < 101)
            return "11-100";
        if(ele.cost >= 101 && ele.cost < 1001)
            return "101-1000";
        return "others";
 };

UPDATE: More elegant Function for cost range as suggested by Holger,

Function<Product, String> costRange = ele -> {
 if(ele.cost < 1) return "others"; 
long i = ele.cost == 1? 1: (long)Math.pow(10, Math.floor(Math.log10(ele.cost-1))); 
return (i|1)+"-"+(i*10); };

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=139482&siteId=1