java常用工具类,优美代码

参考链接:
https://mp.weixin.qq.com/s/XVOxdgyi_ElOTiAXpo4KIw

#返回空集合

Collections.emptyList(); 
或者
Lists.newArrayList()

#集合判空、交集、并集和差集

CollectionUtils.isEmpty(list);
CollectionUtils.isNotEmpty(list);
CollectionUtils.union(list, list2);
CollectionUtils.intersection(list, list2);
CollectionUtils.disjunction(list, list2);
CollectionUtils.subtract(list, list2);

#对象判空

Integer integer = new Integer(1);
Objects.isNull(integer);
Objects.nonNull(integer);

#BooleanUtils
如果你使用了布尔的包装类:Boolean,总感觉有点麻烦,因为它有三种值:null、true、false。我们在处理Boolean对象时,需要经常判空。
头疼!!!
但如果使用BooleanUtils类处理布尔值,心情一下子就愉悦起来了。
有时候,需要判断某个参数不为true,即是null或者false。或者判断不为false,即是null或者true。

Boolean aBoolean = new Boolean(true);
Boolean aBoolean1 = null;
System.out.println(BooleanUtils.isNotTrue(aBoolean));
System.out.println(BooleanUtils.isNotTrue(aBoolean1));
System.out.println(BooleanUtils.isNotFalse(aBoolean));
System.out.println(BooleanUtils.isNotFalse(aBoolean1));

如果你想将true转换成数字1,false转换成数字0,可以使用toInteger方法:

Boolean aBoolean = new Boolean(true);
Boolean aBoolean1 = new Boolean(false);
System.out.println(BooleanUtils.toInteger(aBoolean));
System.out.println(BooleanUtils.toInteger(aBoolean1));

我们有时候需要将包装类Boolean对象,转换成原始的boolean对象,可以使用toBoolean方法。例如:

Boolean aBoolean = new Boolean(true);
Boolean aBoolean1 = null;
System.out.println(BooleanUtils.toBoolean(aBoolean));
System.out.println(BooleanUtils.toBoolean(aBoolean1));
System.out.println(BooleanUtils.toBooleanDefaultIfNull(aBoolean1, false));

#Assert
断言参数是否空,如果不满足条件,则直接抛异常。

String str = null;
Assert.isNull(str, "str必须为空");
Assert.isNull(str, () -> "str必须为空");
Assert.notNull(str, "str不能为空");

断言集合是否空,如果不满足条件,则直接抛异常。

List<String> list = null;
Map<String, String> map = null;
Assert.notEmpty(list, "list不能为空");
Assert.notEmpty(list, () -> "list不能为空");
Assert.notEmpty(map, "map不能为空");

断言条件是否为空

List<String> list = null;
Assert.isTrue(CollectionUtils.isNotEmpty(list), "list不能为空");
Assert.isTrue(CollectionUtils.isNotEmpty(list), () -> "list不能为空");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值