Java8 List 分组 Java 8 Stream 流式计算

 

  1. Map<String, List<StoreInfo>> groupBy = storeList.stream().collect(Collectors.groupingBy(StoreInfo::getStoreCode));storeList 是我的门店列表
    StoreInfo list里的对象
    StoreInfo::getStoreCode 对象分组的条件 我的storeCode是string类型,所有Map 这里要使用string

    说明: 单个属性的分组,其他内容有待补充

列子代码:

  1.1 基础类代码:

package com.wyz.entity;

import java.util.ArrayList;
import java.util.List;

public class Employee {
    
    private String name;
    
    private String city;
    
    private int sales;
    
    

    public Employee(String name, String city, int sales) {
        super();
        this.name = name;
        this.city = city;
        this.sales = sales;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public int getSales() {
        return sales;
    }

    public void setSales(int sales) {
        this.sales = sales;
    }
    
    
    @Override
    public String toString() {
        return "Employee [name=" + name + ", city=" + city + ", sales=" + sales
                + "]";
    }

    public static List<Employee> creteList(){
        List<Employee> eL = new ArrayList<Employee>();
        Employee e1 = new Employee("Alice","London",200);
        eL.add(e1);
        Employee e2 = new Employee("Bob","London",150);
        eL.add(e2);
        Employee e3 = new Employee("Charles","New York",160);
        eL.add(e3);
        Employee e4 = new Employee("Dorothy","Hong Kong",190);
        eL.add(e4);

        return eL;
    }
    

}

1.2  分组测试

package com.wyz;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.junit.Assert;
import org.junit.Test;

import com.wyz.entity.Employee;
public class GroupingBy {

List<Employee> employees = Employee.creteList();

    /**
     * jdk8 之前的
     * 
     */
    @Test
    public void testOldGroup(){
        Map<String,List<Employee>> result = new HashMap<String, List<Employee>>();
        for(Employee e :employees){
            String city = e.getCity();
            List<Employee> empsInCity = result.get(city);
            if(empsInCity == null){
                empsInCity = new ArrayList<Employee>();
                result.put(city, empsInCity);
            }
            empsInCity.add(e);
        }
        System.out.println(result.toString());
    }
    // 输出结果

//  {New York=[Employee [name=Charles, city=New York, sales=160]], Hong Kong=[Employee [name=Dorothy, city=Hong Kong, sales=190]], //London=[Employee [name=Alice, city=London, sales=200], Employee [name=Bob, city=London, sales=150]]}

/**
     * jdk8 的分组实现
     */
    @Test
    public void testGroupJ8(){
        Map<String, List<Employee>> employeesByCity =
                employees.stream().collect(Collectors.groupingBy(Employee::getCity));
        System.out.println(employeesByCity);
     }

// 输出结果:

//{New York=[Employee [name=Charles, city=New York, sales=160]], Hong Kong=[Employee [name=Dorothy, city=Hong Kong, sales=190]], //London=[Employee [name=Alice, city=London, sales=200], Employee [name=Bob, city=London, sales=150]]}

/**
     * jdk8 统计
     */
    @Test
    public void testGroupJ8NumEmployeesByCity(){

        Map<String, Long> numEmployeesByCity = employees.stream().collect(
                Collectors.groupingBy(Employee::getCity, Collectors.counting()));
        Assert.assertEquals(numEmployeesByCity.get("London").longValue(),2);

          System.out.println(numEmployeesByCity);

    }
// 输出结果

// {New York=1, Hong Kong=1, London=2}

/**
     * 求平均值
     */
    @Test
    public void groupByAverageTest(){
        
        Map<String,Double> employeesByCity = 
                employees.stream().collect(Collectors.groupingBy(
                        Employee::getCity,Collectors.averagingInt(Employee::getSales)));
        System.out.println(employeesByCity);
    }
// 输出结果

{New York=160.0, Hong Kong=190.0, London=175.0}

/**
     * jdk8 分区
     */
    @Test
    public void  partitioned(){
        
        Map<Boolean,List<Employee>> partitioned = 
                employees.stream().collect(Collectors.partitioningBy(e-> e.getSales()>150));
        System.out.println(partitioned);
    }

// 输出结果

//{false=[Employee [name=Bob, city=London, sales=150]], true=[Employee [name=Alice, city=London, sales=200], Employee [name=Charles, //city=New York, sales=160], Employee [name=Dorothy, city=Hong Kong, sales=190]]}

    @Test
    public void partitionedAdGroupBy(){
        Map<Boolean,Map<String,Long>> result =
                employees.stream().collect(Collectors.partitioningBy(e ->e.getSales() >150,
                        Collectors.groupingBy(Employee::getCity,Collectors.counting())));
        
        System.out.println(result);
    }
    // {false={London=1}, true={New York=1, Hong Kong=1, London=1}}
    }

其他列子:

2.1 Group by a List and display the total count of it.

package com.wyz;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 *  Group by a List and display the total count of it.
 * @author hjy-0
 *
 */
public class Java8Example1 {

    public static void main(String[] args){
         List<String> items =
                    Arrays.asList("apple", "apple", "banana",
                            "apple", "orange", "banana", "papaya");    
         
          Map<String,Long> result = items.stream().collect(
                  Collectors.groupingBy(Function.identity(),Collectors.counting()));
          
          System.out.println(result);
         }
}
// 输出结果

{papaya=1, orange=1, banana=2, apple=3}
2.2 Add sorting.

package com.wyz;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Add sorting.
 * @author hjy-0
 *
 */
public class java8Example2 {

    
    public static void main(String[] args) {
        
        List<String> items = Arrays.asList("apple","apple","banana",
                "apple","orange","banana","papaya");
        
        Map<String,Long> result =
                items.stream().collect(
                        Collectors.groupingBy(Function.identity(),Collectors.counting()));
        
        System.out.println(result);
        Map<String,Long> finalMap = new LinkedHashMap();
        
        // sort a map and add to finalMap
        result.entrySet().stream().sorted(
                Map.Entry.<String,Long>comparingByValue().
                reversed()).forEachOrdered(e->finalMap.put(e.getKey(), e.getValue()));;
                
        System.out.println(finalMap);
                
    }
}

// 输出结果#

{papaya=1, orange=1, banana=2, apple=3}
{apple=3, banana=2, papaya=1, orange=1}
// 输出结果#

2.3 Group by the name + Count or Sum the Qty.

package com.wyz;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.wyz.entity.Item;

/**
 * Group by the name + Count or Sum the Qty.
 * @author hjy-0
 *
 */
public class Java8Examples3 {
    
    public static void main(String[] args){
        List<Item> items = Arrays.asList(
                new Item("apple", 10, new BigDecimal("9.99")),
                new Item("banana", 20, new BigDecimal("19.99")),
                new Item("orang", 10, new BigDecimal("29.99")),
                new Item("watermelon", 10, new BigDecimal("29.99")),
                new Item("papaya", 20, new BigDecimal("9.99")),
                new Item("apple", 10, new BigDecimal("9.99")),
                new Item("banana", 10, new BigDecimal("19.99")),
                new Item("apple", 20, new BigDecimal("9.99"))
                
                );
        
        Map<String,Long> counting = items.stream().collect(
                Collectors.groupingBy(Item::getName,Collectors.counting())
                );
        
        System.out.println(counting);
        
        Map<String,Integer> sum = items.stream().collect(
                Collectors.groupingBy(Item::getName,Collectors.summingInt(Item::getQty)));
        
        System.out.println(sum);
    }

}
// 输出结果#

{papaya=1, banana=2, apple=3, orang=1, watermelon=1}
{papaya=20, banana=30, apple=40, orang=10, watermelon=10}
// 输出结果#

2.4 Group by Price – Collectors.groupingBy and Collectors.mapping example.

package com.wyz;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.wyz.entity.Item;

/**
 * Group by Price – Collectors.groupingBy and Collectors.mapping example.
 * @author hjy-0
 *
 */
public class Java8Example4 {
    
    public static void main(String[] args){
        //3 apple, 2 banana, others 1
        
        List<Item> items = Arrays.asList(
                new Item("apple", 10, new BigDecimal("9.99")),
                new Item("banana", 20, new BigDecimal("19.99")),
                new Item("orang", 10, new BigDecimal("29.99")),
                new Item("watermelon", 10, new BigDecimal("29.99")),
                new Item("papaya", 20, new BigDecimal("9.99")),
                new Item("apple", 10, new BigDecimal("9.99")),
                new Item("banana", 10, new BigDecimal("19.99")),
                new Item("apple", 20, new BigDecimal("9.99"))
                );
        
        // group by price
        Map<BigDecimal,List<Item>> groupByPriceMap =
                items.stream().collect(Collectors.groupingBy(Item::getPrice));
        
        System.out.println(groupByPriceMap);
        
        // group by price ,user 'Mapping' to convert List<Item> to Set<String>
        
        Map<BigDecimal,Set<String>> result =
                items.stream().collect(Collectors.groupingBy(Item::getPrice,
                        Collectors.mapping(Item::getName, Collectors.toSet())));
        
           System.out.println(result);
        }

}
// 输出结果

{19.99=[Item [name=banana, qty=20, price=19.99], Item [name=banana, qty=10, price=19.99]], 29.99=[Item [name=orang, qty=10, price=29.99], Item [name=watermelon, qty=10, price=29.99]], 9.99=[Item [name=apple, qty=10, price=9.99], Item [name=papaya, qty=20, price=9.99], Item [name=apple, qty=10, price=9.99], Item [name=apple, qty=20, price=9.99]]}
{19.99=[banana], 29.99=[orang, watermelon], 9.99=[papaya, apple]}
 

//输出结果

转载于:https://my.oschina.net/kuchawyz/blog/3038108

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值