Java Lambda List转Map代码实例
在有些开发场景,需要对List对象列表进行过滤处理,并将有用的数据存放到Map中。
例如:告警对象,包含告警uuid(alarmUuid)和设备uuid(objUuid),需要对objUuid=-1的告警进行过滤,并将过滤后告警数据的alarmUuid和objUuid以键值对的形式保存到Map中。
1、告警对象定义如下:
/** *CreatedbyMiracleLunaon2020/3/16 */ publicclassAlarmInfoResponse{ privateStringalarmUuid; privateStringobjUuid; publicAlarmInfoResponse(StringalarmUuid,StringobjUuid){ this.alarmUuid=alarmUuid; this.objUuid=objUuid; } publicStringgetAlarmUuid(){ returnalarmUuid; } publicvoidsetAlarmUuid(StringalarmUuid){ this.alarmUuid=alarmUuid; } publicStringgetObjUuid(){ returnobjUuid; } publicvoidsetObjUuid(StringobjUuid){ this.objUuid=objUuid; } @Override publicStringtoString(){ return"AlarmInfoResponse{"+ "alarmUuid='"+alarmUuid+'\''+ ",objUuid='"+objUuid+'\''+ '}'; } }
2、过滤代码如下:
/** *CreatedbyMiracleLunaon2020/3/16 */ publicclassLambdaFilterListToMap{ publicstaticvoidmain(String[]args){ ListalarmInfoResponseList=newArrayList<>(); AlarmInfoResponseresponse0=newAlarmInfoResponse("alarm0","-1"); AlarmInfoResponseresponse1=newAlarmInfoResponse("alarm1","1"); AlarmInfoResponseresponse2=newAlarmInfoResponse("alarm2","2"); AlarmInfoResponseresponse3=newAlarmInfoResponse("alarm3","3"); alarmInfoResponseList.add(response0); alarmInfoResponseList.add(response1); alarmInfoResponseList.add(response2); alarmInfoResponseList.add(response3); //方式1:先使用foreach遍历(遍历过程中条件判断) Map alarmObjUuidMap1=newHashMap<>(); alarmInfoResponseList.forEach(alarmInfoResponse->{ if(!"-1".equals(alarmInfoResponse.getObjUuid())){ alarmObjUuidMap1.put(alarmInfoResponse.getAlarmUuid(),alarmInfoResponse.getObjUuid()); } }); System.out.println("=============方式1===================="); alarmObjUuidMap1.forEach((alarmUuid,objUuid)->System.out.println(alarmUuid+":"+objUuid)); //方式2:使用流过滤,再使用foreach遍历 Map alarmObjUuidMap2=newHashMap<>(); alarmInfoResponseList.stream(). filter(alarmInfoResponse->!"-1".equals(alarmInfoResponse.getObjUuid())). forEach(alarmInfoResponse->alarmObjUuidMap2.put(alarmInfoResponse.getAlarmUuid(),alarmInfoResponse.getObjUuid())); System.out.println("\n=============方式2===================="); alarmObjUuidMap2.forEach((alarmUuid,objUuid)->System.out.println(alarmUuid+":"+objUuid)); } }
3、运行结果如下:
=============方式1====================
alarm2:2
alarm1:1
alarm3:3=============方式2====================
alarm2:2
alarm1:1
alarm3:3
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。