java8lambda最頻繁操作及理解

數據庫查詢往往返回的是list,我們可能需要進行進一步的聚合,總結如下:

list轉list:
stream().collect(Collectors.toList());

list轉Map:
stream().collect(Collectors.toMap(MyClass::getId,Function.identity(),(a,b) -> a));

list分組map:.
stream().collect(Collectors.groupingBy(MyClass::getId));

		MyClassReqDTO reqDTO = new MyClassReqDTO();
        reqDTO.setCode("519745072412");
        List<MyClass> pojoList = MyClassManager.listMyClass(reqDTO);
        
        
        //list轉list
        List<MyClass> idList1 = pojoList.stream().map(a -> a).collect(Collectors.toList());

        //取出某一字段 組裝list
        List<Long> idList = pojoList.stream().map(MyClass::getId).collect(Collectors.toList());

		//求list長度
        Long count = pojoList.stream().count();

        // list轉map 並去重
        Map<Long,MyClass> map1 = pojoList.stream().collect(Collectors.toMap(MyClass::getId,Function.identity(),(a,b) -> a));

        // 按條件過濾 list轉map
        Map<Long,MyClass> map3 = pojoList.stream().filter( c -> c.getId() < 4).collect(Collectors.toMap(MyClass::getId,Function.identity(),(a,b) -> a));

        //分組轉map
        Map<Long,List<MyClass>> map2 = pojoList.stream().collect(Collectors.groupingBy(MyClass::getId));

        //求和
        Long sum = pojoList.stream().mapToLong(MyClass::getId).sum();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章