Java Lambda List轉(zhuǎn)Map代碼實例
在有些開發(fā)場景,需要對 List 對象列表進(jìn)行過濾處理,并將有用的數(shù)據(jù)存放到Map中。
例如:告警對象,包含告警uuid(alarmUuid) 和 設(shè)備uuid(objUuid),需要對 objUuid = -1的告警進(jìn)行過濾,并將過濾后告警數(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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. msxml3.dll 錯誤 800c0019 系統(tǒng)錯誤:-2146697191解決方法2. WMLScript的語法基礎(chǔ)3. ASP中解決“對象關(guān)閉時,不允許操作。”的詭異問題……4. 解決ASP中http狀態(tài)跳轉(zhuǎn)返回錯誤頁的問題5. html小技巧之td,div標(biāo)簽里內(nèi)容不換行6. xml中的空格之完全解說7. XML入門的常見問題(四)8. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁9. ASP中if語句、select 、while循環(huán)的使用方法10. ASP動態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗分享
