针对java8 stream的常用处理,针对集团分布式mysql的诸多的限制要求,数据的处理减少对数据库的操作,通过java方式处理相比就会增加集合之间数据处理的使用。简单整理一下几个filter、map、collect、groupingBy
1.filter 过滤
//过滤所有List 对象nbr不为空的对象
List mktResNumInstList = batchModNumInstReq.getMktResNumInsts();
List mktNbrList = mktResNumInstList.stream(). filter(t->StringUtils.isNotEmptyOrNull(t.getMktResInstNbr()))
.collect(Collectors.toList());
2.获取一个对象某个属性的集合
List list= xxxxxxx;
list.stream(). map(t -> t.getMktResInstId()).collect(Collectors.toList()));
3.collect 收集器
上面的两个例子中都用到了collect( Collectors.toList()) 最后生成一个list;当然处理list还可以转化为map
下面的例子是将一个List list对象转换成Map map对象
Map map=list.stream().collect( Collectors.toMap(MktResNumInst::getMktResInstId,MktResNumInst->MktResNumInst ));
而map对象的key 可以用对象中的某个属性字段本例中使用的id
( MktResNumInst::getMktResInstId),value为对象本身MktResNumInst->MktResNumInst。
4.集合合并处理
之所以将对象变成map是为了两个对象的合并处理–>如下:
List numInstList = new ArrayList ();
criteria.andMktResInstIdIn(list.stream().map(t -> t.getMktResInstId()).collect(Collectors.toList()));
numInstList = mktResNumInstMapper.selectByExample(example);
//将传入的list转成map
Map map=list.stream().collect(Collectors.toMap( MktResNumInst::getMktResInstId,MktResNumInst->MktResNumInst));
//合并list
numInstList.forEach(n->{
if( map.containsKey(n.getMktResInstId())){//判断两个集合的id
//将map中的对象给 numInstList 里的对象赋值
MktResNumInst obj = map.get(n.getMktResInstId());
n.setMinConsume(obj.getMinConsume());
n.setDepositAmount(obj.getDepositAmount());
}
});
5.groupingBy 分组的使用 也是归属collect 使用里
//通过校验返回可操作的list对象,并对对象中的id通过分片规则的方式分组,以方便批量的处理(集团mysql必须分片)
Map > routeMap =doList.stream().
collect( Collectors.groupingBy(t->RouteMod.shardAlgorithm(t.getMktResInstId())));
以上是结合实际开发,针对java8集合使用的简单总结