使用Java 8 Lambda表达式将实体映射到DTO的操作

网友投稿 222 2023-03-23

使用Java 8 Lambda表达式将实体映射到DTO的操作

当我们需要将DTO转换为实体(Hibernate实体等)并向后转换时,我们都会面临混乱的开销代码。

在我的示例中,我将用java 8演示代码如何变得越来越短。

让我们创建目标DTO:

public class ActiveUserListDTO {

public ActiveUserListDTO() {

}

public ActiveUserListDTO(UserEntity userEntity) {

this.username = userEntithttp://y.getUsername();

...

}

}

使用Spring数据JPA API检索所有实体的简单查找方法:

userRepository.findAll();

Problem:

Find.All() method signature (like many others) returns java.lang.Iterable

java.lang.Iterable findAll(java.lang.Iterable iterable)

我们不能使用java.lang.Iterable(*在集合上运行的Streams来制作Stream。每个Collection都是Iterable,但并不是每个Iterable都是必需的Collection)。

那么,如何获取Stream对象以获得Java8 Lambda的Power?

让我们使用StreamSupport对象将Iterable转换为Stream:

Stream userEntityStream = StreamSupport.stream(userRepository.findAll().spliterator(), falshttp://e);

大。 现在,我们掌握了Stream,这是Java 8 Labmda的关键!

剩下的就是地图和收集:

List activeUserListDTOs =

userEntities.stream().map(ActiveUserList::new).collect(Collectors.toList());

我正在使用Java 8 Method Reference,因此将每个实体初始化(和映射)到dto中。

因此,让我们对所有内容进行简短介绍:

List activeUserListDTOs=StreamSupport.stream(userRepository.findAll().spliterator(), false).map(ActiveUserList::new).collect(Collectors.toList());

那很整齐!!

补充知识:java8中使用Lambda表达式将list中实体类的两个字段转Map

代码:

List list = new ArrayList<>();

Map map = list.stream().collect(Collectors.toMap(Entity::getId, Entity::getType));

常用的lambda表达式:

**

* List -> Map

* 需要注意的是:

* toMap 如果集合对象有重复的key,会报错Duplicate key ....

* apple1,apple12的id都为1。

* 可以用 (k1,k2)->k1 来设置http://,如果有重复的key,则保留key1,舍弃key2

*/

Map 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 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 naturalDayList;

BigDecimal total = naturalDayList.stream().reduce(BigDecimal.ZERO, BigDecimal::add);

分组函数

Map> 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);

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

上一篇:Java GZip 基于内存实现压缩和解压的方法
下一篇:api平台 (api平台)(4分钟之前已更新)
相关文章

 发表评论

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