Java Lambda List转Map代码实例

网友投稿 274 2022-12-11


Java Lambda List转Map代码实例

在有些开发场景,需要对 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='"http:// + objUuid + '\'' +

'}';

}

}

2、过滤代码如下:

/**

* Created by Miracle Luna on 2020/3/16

*/

public class LambdaFilterListToMap {

public static void main(String[] args) {

List 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 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 alarmObjUuidMap2 = new HashMap<>();

alarmInfoResponseList.streamhttp://().

filter(alarmInfoResponse -> !"-1".equals(alarmInfoResponse.getObjUuid())).

forEach(alarmInfoResponse -> alarmObjUuidMap2.put(alarmInfoResponse.getAlarmUuid(), alarmInfoResponse.getObjUuid()));

System.out.println("\n============= 方式2 ====================");

alarmObjUuidMap2.forEach((alarmUuid, objUuid) -> System.txAkjout.println(alarmUuid + " : " + objUuid));

}

}

3、运行结果如下:

============= 方式1 ====================

alarm2 : 2

alarm1 : 1

alarm3 : 3

============= 方式2 ====================

alarm2 : 2

alarm1 : 1

alarm3 : 3


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:java链表应用
下一篇:SpringCloud Zuul过滤器和谷歌Gauva实现限流
相关文章

 发表评论

暂时没有评论,来抢沙发吧~