當我們需要將DTO轉換為實體(Hibernate實體等)并向后轉換時,我們都會面臨混亂的開銷代碼。
在我的示例中,我將用Java 8演示代碼如何變得越來越短。
讓我們創建目標DTO:
1
2
3
4
5
6
7
8
9
|
public class ActiveUserListDTO { public ActiveUserListDTO() { } public ActiveUserListDTO(UserEntity userEntity) { this .username = userEntity.getUsername(); ... } } |
使用Spring數據JPA API檢索所有實體的簡單查找方法:
1
2
3
4
|
userRepository.findAll(); Problem: Find.All() method signature (like many others) returns java.lang.Iterable<T> java.lang.Iterable<T> findAll(java.lang.Iterable<ID> iterable) |
我們不能使用java.lang.Iterable(*在集合上運行的Streams來制作Stream。每個Collection都是Iterable,但并不是每個Iterable都是必需的Collection)。
那么,如何獲取Stream對象以獲得Java8 Lambda的Power?
讓我們使用StreamSupport對象將Iterable轉換為Stream:
Stream<UserEntity> userEntityStream = StreamSupport.stream(userRepository.findAll().spliterator(), false);
大。 現在,我們掌握了Stream,這是Java 8 Labmda的關鍵!
剩下的就是地圖和收集:
List<ActiveUserList> activeUserListDTOs =
userEntities.stream().map(ActiveUserList::new).collect(Collectors.toList());
我正在使用Java 8 Method Reference,因此將每個實體初始化(和映射)到dto中。
因此,讓我們對所有內容進行簡短介紹:
List<ActiveUserList> activeUserListDTOs=StreamSupport.stream(userRepository.findAll().spliterator(), false).map(ActiveUserList::new).collect(Collectors.toList());
那很整齊!!
補充知識:java8中使用Lambda表達式將list中實體類的兩個字段轉Map
代碼:
List<Entity> list = new ArrayList<>();
Map<Integer, String> map = list.stream().collect(Collectors.toMap(Entity::getId, Entity::getType));
常用的lambda表達式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
** * List -> Map * 需要注意的是: * toMap 如果集合對象有重復的key,會報錯Duplicate key .... * apple1,apple12的id都為 1 。 * 可以用 (k1,k2)->k1 來設置,如果有重復的key,則保留key1,舍棄key2 */ Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1)); 安照某一字段去重 list = list.stream().filter(distinctByKey(p -> ((ModCreditColumn) p).getFieldCode())).collect(Collectors.toList()); List<Double> unitNetValue = listIncreaseDto.stream().map(IncreaseDto :: getUnitNetValue).collect(Collectors.toList()); //求和 對象List BigDecimal allFullMarketPrice = entityList.stream().filter(value -> value.getFullMarketPrice()!= null ).map(SceneAnalysisRespVo::getFullMarketPrice).reduce(BigDecimal.ZERO, BigDecimal::add); List<BigDecimal> naturalDayList; BigDecimal total = naturalDayList.stream().reduce(BigDecimal.ZERO, BigDecimal::add); 分組函數 Map<String, List<SceneAnalysisRespVo>> groupMap = total.getGroupList().stream().collect(Collectors.groupingBy(SceneAnalysisRespVo::getVmName)); //DV01之和 BigDecimal allDV01 = values.stream().filter(sceneAnalysisRespVo -> sceneAnalysisRespVo.getDv() != null ).map(SceneAnalysisRespVo::getDv).reduce(BigDecimal.ZERO, BigDecimal::add); |
以上這篇使用Java 8 Lambda表達式將實體映射到DTO的操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/dnc8371/article/details/107267037