java8中使用Lambda表达式将list中实体类的两个字段转Map

代码:

List list = new ArrayList<>();
Map map = list.stream().collect(Collectors.toMap(Entity::getId, Entity::getType));
		

常用的lambda表达式:

**
 * List -> Map
 * 需要注意的是:
 * toMap 如果集合对象有重复的key,会报错Duplicate key ....
 *  apple1,apple12的id都为1。
 *  可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
 */
Map appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));

安照某一字段去重
list = list.stream().filter(distinctByKey(p -> ((ModCreditColumn) p).getFieldCode())).collect(Collectors.toList());




List unitNetValue = listIncreaseDto.stream().map(IncreaseDto :: getUnitNetValue).collect(Collectors.toList());

//求和  对象List
BigDecimal allFullMarketPrice = entityList.stream().filter(value -> value.getFullMarketPrice()!= null).map(SceneAnalysisRespVo::getFullMarketPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
 
 List  naturalDayList;
 BigDecimal total = naturalDayList.stream().reduce(BigDecimal.ZERO, BigDecimal::add);



分组函数
Map> groupMap = total.getGroupList().stream().collect(Collectors.groupingBy(SceneAnalysisRespVo::getVmName));



//DV01之和
BigDecimal allDV01 = values.stream().filter(sceneAnalysisRespVo -> sceneAnalysisRespVo.getDv() != null).map(SceneAnalysisRespVo::getDv).reduce(BigDecimal.ZERO, BigDecimal::add);

 

你可能感兴趣的:(java)