java常用工具类,优美代码
#返回空集合
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不能为空");