*需求说明:
* 涉及一个对外提供服务的接口,支持调用方传入多个账户编号查询订单
public class Case_4 {
@Data
@AllArgsConstructor
class Order {
private Integer orderId;
private String accountId;
}
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 List<Order> queryOrderByAccountIds(List<String> accountIds){
List<Order> orderList = selectFromDB(accountIds);
return orderList;
}
public Map<String,List<Order>> queryOrderByAccountIdsMap(List<String> accountIds){
Map<String, List<Order>> result = Optional.ofNullable(selectFromDB(accountIds))
.map(List::stream)
.orElseGet(Stream::empty)
.collect(Collectors.groupingBy(
order -> order.getAccountId()
));
return result;
}
@Test
public void test(){
List<Order> orders_1 = queryOrderByAccountIds(Lists.newArrayList("张三", "李四", "王五"));
Map<String, List<Order>> orders_2 = queryOrderByAccountIdsMap(
Lists.newArrayList("张三", "李四", "王五")
);
System.out.println(JSON.toJSONString(orders_1,true));
System.out.println("==========两种结果对比参考=============");
System.out.println(JSON.toJSONString(orders_2,true));
}
}
j结果展示
[
{"accountId":"张三","orderId":0},
{"accountId":"李四","orderId":1},
{"accountId":"王五","orderId":2},
{"accountId":"张三","orderId":3},
{"accountId":"李四","orderId":4},
{"accountId":"王五","orderId":5},
{"accountId":"张三","orderId":6},
{"accountId":"李四","orderId":7},
{"accountId":"王五","orderId":8},
{"accountId":"张三","orderId":9}
]
==========两种结果对比参考=============
{
"李四":
[{"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}]
}
|