代码优雅秘籍1 - 使用Lambda表达式代替if对集合或对象进行判空

本文对应源码:欢迎关注我的公众号nrsc,并在同名文章中获取本文对应源码。

1 本文所需工具类包

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

2 使用Lambda表达式代替if对集合进行判空

2.1 List集合

先看如下代码:

public List<UserInfoDTO> getUserInfoListByIds_001(List<Long> userIds) {
    List<UserInfo> userInfos = collectionDemoRepository.getUserInfoListByIds(userIds);
   
    //为了防止下面convert2DTO方法出现NPE,
    //这里要先判断集合是否为空,如果是,直接返回空集合
    if (CollectionUtils.isEmpty(userInfos)) {
        return Collections.emptyList();
    }

    //如果集合不为空,将pojo对象转成DTO
    return userInfos.stream()
            .map(UserInfoConverter::convert2DTO)
            .collect(Collectors.toList());
}

相信与之类似的代码你一定写过或见过。

如代码中注释所述,其实代码中的if判断,主要是为了防止convert2DTO方法出现NPE,那能不能将上面的代码写得更优雅一些呢?

我的方法如下,即一行lambda表达式,既把NPE的问题解决掉,又完成具体的业务行为:

public List<UserInfoDTO> getUserInfoListById_002(List<Long> userIds) {
    return ListUtils.emptyIfNull(
                    collectionDemoRepository.getUserInfoListByIds(userIds)
            )
            .stream()
            .map(UserInfoConverter::convert2DTO)
            .collect(Collectors.toList());
}

2.2 引申 - 其他集合

2.1节所示,List集合我们可以用ListUtils.emptyIfNull方法, 其实其他常见的集合也都有与之类似的方法,比如:

  • Map集合对应方法源码
/**
* Returns an immutable empty map if the argument is <code>null</code>,
* or the argument itself otherwise.
*
* @param <K> the key type
* @param <V> the value type
* @param map the map, possibly <code>null</code>
* @return an empty map if the argument is <code>null</code>
*/
public static <K,V> Map<K,V> emptyIfNull(final Map<K,V> map) {
  return map == null ? Collections.<K,V>emptyMap() : map;
}
  • Set集合对应方法源码
/**
 * Returns an immutable empty set if the argument is <code>null</code>,
 * or the argument itself otherwise.
 *
 * @param <T> the element type
 * @param set the set, possibly <code>null</code>
 * @return an empty set if the argument is <code>null</code>
 */
public static <T> Set<T> emptyIfNull(final Set<T> set) {
    return set == null ? Collections.<T>emptySet() : set;
}
  • 顶层集合Collection对应方法源码
/**
 * Returns an immutable empty collection if the argument is <code>null</code>,
 * or the argument itself otherwise.
 *
 * @param <T> the element type
 * @param collection the collection, possibly <code>null</code>
 * @return an empty collection if the argument is <code>null</code>
 */
public static <T> Collection<T> emptyIfNull(final Collection<T> collection) {
    return collection == null ? CollectionUtils.<T>emptyCollection() : collection;
}

2 使用Lambda表达式代替if对单个对象进行判空

先看如下代码:

public UserInfoDTO getUserInfoById_001(Long userId) {
   
    //为了防止下面convert2DTO方法出现NPE,
    //这里要先判断对象是否为空,如果是,直接返回null
    UserInfo userInfo = collectionDemoRepository.getUserInfoById(userId);
    if (userInfo == null) {
        return null;
    }
    
    //如果对象不为空,将pojo对象转成DTO
    return UserInfoConverter.convert2DTO(userInfo);
}

相信看完2.1节,你肯定很自然地就会在想上面的代码是不是也可以用一个lambda表达式搞定?

是的,可以!

我们可以借助Optional类的ofNullable方法,代码如下:

public UserInfoDTO getUserInfoById_002(Long userId) {
  return Optional.ofNullable(collectionDemoRepository.getUserInfoById(userId))
          .map(UserInfoConverter::convert2DTO)//如果不为null走map方法
          .orElse(null);//如果为null,就返回null
}

非常感谢您宝贵的时间,愿本文能给您带来些许帮助!

本文由mdnice多平台发布

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nrsc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值