JDK8 Stream分组功能 Collectors.groupingBy 两种写法

1。针对list()类型的分组和改造(stream流)

Map<String, List<String>> sortFood = 
FoodList.stream().collect(Collectors.groupingBy(Food::getColor,
  Collectors.mapping(Food::getSort, toList())));
sortFood.forEach((k, v) -> {
	System.out.println(k + "的零食有");
	v.forEach(System.out::println);
});

干的 的零食有:
干果
薯片
饼干
湿的零食有:
罐头
桃汁
public class SmsReceipt {

    /**
     * 接触工单id
     */
    private Long contactId;

    /**
     * 短信状态
     */
    private String state;

    /**
     * 分片id
     */
    private Long partId;

    public Long getContactId() {
        return contactId;
    }

    public void setContactId(Long contactId) {
        this.contactId = contactId;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public Long getPartId() {
        return partId;
    }

    public void setPartId(Long partId) {
        this.partId = partId;
    }
}
Map<Long, List<Long>> dlvMap = 
dlvSmsReceiptList.stream().collect(
             Collectors.groupingBy(SmsReceipt::getPartId,
             Collectors.mapping(SmsReceipt::getContactId, 
             Collectors.toList())
             ));
             

根据分片Id,将contactId进行分片处理。

2.针对mapping类型的遍历(stream流)

batchResultMap.entrySet().stream().forEach(entry -> {});

 private void updateMccBatch(Map<Long, StateNumCounter> batchResultMap) {
        if (batchResultMap.isEmpty()) {
            return;
        }

        List<MccBatch> batchList = new ArrayList<>();

        batchResultMap.entrySet().stream().forEach(entry -> {
            StateNumCounter batchCounter = entry.getValue();

            MccBatch batch = new MccBatch();
            batch.setId(entry.getKey());
            batch.setSucceedNum(batchCounter.getSucceedNum());
            batch.setFailedNum(batchCounter.getFailedNum());
            batch.setPendingNum(batchCounter.getPendingNum());
            batchList.add(batch);
        });

        batchDataServ.batchUpdateMccBatchResult(batchList);
    }
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐