1 重点:
1.1 定义map类型的方法(详见实战案例)
1.2 Optional方法非空方法的使用
1.3 分组方法的应用(详见实战案例)
2 分组demo
分组demo需求:
给出一部分订单号,按照这些订单定的账号分组进行查询
测试类:
package com.imooc.zhangxiaoxi.stream.cases; import com.alibaba.fastjson.JSON; import com.google.common.collect.Lists; import lombok.AllArgsConstructor; import lombok.Data; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; /** * 类名称:CaseFour * ******************************** * <p> * 类描述:案例四 * 重点讲解:group的使用方式 * * @author zhangxiaoxi * @date 下午8:39 */ public class CaseFour { /*@Data @AllArgsConstructor*/ class Order { /** * 订单编号 */ private Integer orderId; /** * 账户编号 */ private String accountId; public Order(Integer orderId, String accountId) { this.orderId = orderId; this.accountId = accountId; } public Integer getOrderId() { return orderId; } public String getAccountId() { return accountId; } } /** * 模拟数据库查询 * @param accountIds * @return */ public List<Order> selectFromDB(List<String> accountIds) { List<Order> orderList = new ArrayList<>(); for (int i = 0; i < 10; i++) { orderList.add( new Order(i, accountIds.get(i % accountIds.size()))); } return orderList; } public Map<String,List<Order>> queryOrderByAccountID(List<String> orderList){ return Optional.ofNullable(selectFromDB(orderList)) //如果不为空 .map(List::stream) //如果为空 .orElseGet(Stream::empty) .collect(Collectors.groupingBy(order->order.getAccountId())); } @Test public void testOrder(){ Map<String, List<Order>> orders = queryOrderByAccountID(Lists.newArrayList("秦始皇", "汉武帝", "赵武灵王")); System.out.println(JSON.toJSONString(orders,true)); } }
打印日志:
{ "汉武帝":[ { "accountId":"汉武帝", "orderId":1 }, { "accountId":"汉武帝", "orderId":4 }, { "accountId":"汉武帝", "orderId":7 } ], "秦始皇":[ { "accountId":"秦始皇", "orderId":0 }, { "accountId":"秦始皇", "orderId":3 }, { "accountId":"秦始皇", "orderId":6 }, { "accountId":"秦始皇", "orderId":9 } ], "赵武灵王":[ { "accountId":"赵武灵王", "orderId":2 }, { "accountId":"赵武灵王", "orderId":5 }, { "accountId":"赵武灵王", "orderId":8 } ] } Process finished with exit code 0