Java Lambda List转Map代码实例

时间:2021-05-20

在有些开发场景,需要对 List 对象列表进行过滤处理,并将有用的数据存放到Map中。

例如:告警对象,包含告警uuid(alarmUuid) 和 设备uuid(objUuid),需要对 objUuid = -1的告警进行过滤,并将过滤后告警数据的alarmUuid和 objUuid以键值对的形式保存到Map中。

1、告警对象定义如下:

/** * Created by Miracle Luna on 2020/3/16 */public class AlarmInfoResponse { private String alarmUuid; private String objUuid; public AlarmInfoResponse(String alarmUuid, String objUuid) { this.alarmUuid = alarmUuid; this.objUuid = objUuid; } public String getAlarmUuid() { return alarmUuid; } public void setAlarmUuid(String alarmUuid) { this.alarmUuid = alarmUuid; } public String getObjUuid() { return objUuid; } public void setObjUuid(String objUuid) { this.objUuid = objUuid; } @Override public String toString() { return "AlarmInfoResponse{" + "alarmUuid='" + alarmUuid + '\'' + ", objUuid='" + objUuid + '\'' + '}'; }}

2、过滤代码如下:

/** * Created by Miracle Luna on 2020/3/16 */public class LambdaFilterListToMap { public static void main(String[] args) { List<AlarmInfoResponse> alarmInfoResponseList = new ArrayList<>(); AlarmInfoResponse response0 = new AlarmInfoResponse("alarm0", "-1"); AlarmInfoResponse response1 = new AlarmInfoResponse("alarm1", "1"); AlarmInfoResponse response2 = new AlarmInfoResponse("alarm2", "2"); AlarmInfoResponse response3 = new AlarmInfoResponse("alarm3", "3"); alarmInfoResponseList.add(response0); alarmInfoResponseList.add(response1); alarmInfoResponseList.add(response2); alarmInfoResponseList.add(response3); // 方式1:先使用foreach遍历(遍历过程中条件判断) Map<String, String> alarmObjUuidMap1 = new HashMap<>(); 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<String, String> alarmObjUuidMap2 = new HashMap<>(); 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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章