国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

Java Lambda List轉(zhuǎn)Map代碼實例

瀏覽:75日期:2022-09-04 11:55:51

在有些開發(fā)場景,需要對 List 對象列表進行過濾處理,并將有用的數(shù)據(jù)存放到Map中。

例如:告警對象,包含告警uuid(alarmUuid) 和 設備uuid(objUuid),需要對 objUuid = -1的告警進行過濾,并將過濾后告警數(shù)據(jù)的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、運行結(jié)果如下:

============= 方式1 ====================alarm2 : 2alarm1 : 1alarm3 : 3

============= 方式2 ====================alarm2 : 2alarm1 : 1alarm3 : 3

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標簽: Java
相關(guān)文章:
主站蜘蛛池模板: 和林格尔县| 库车县| 叶城县| 文山县| 海盐县| 滨海县| 手游| 昂仁县| 桑植县| 平和县| 滦南县| 江孜县| 西丰县| 鄢陵县| 上思县| 中宁县| 洛浦县| 汝阳县| 江津市| 夹江县| 从化市| 临高县| 桃源县| 苍山县| 厦门市| 盖州市| 花莲县| 珲春市| 五原县| 青海省| 寻乌县| 布拖县| 樟树市| 资溪县| 红原县| 高陵县| 山丹县| 房产| 丹凤县| 武宁县| 鄄城县|