通过CollectionUtils工具类判断集合是否为空

先引入CollectionUtils工具类:

import org.apache.commons.collections4.CollectionUtils;

工具类中的部分方法:

public static boolean isEmpty(Collection<?> coll) {
return coll == null || coll.isEmpty();
}

public static boolean isNotEmpty(Collection<?> coll) {
return !isEmpty(coll);
}

测试:

@Test
    public void test4(){
        boolean empty1 = CollectionUtils.isEmpty(null);
        System.out.println(empty1);
        boolean empty2 = CollectionUtils.isEmpty(new ArrayList());
        System.out.println(empty2);
        List list=new ArrayList();
        list.add("helloworld1");
        list.add("helloworld2");
        boolean empty3 = CollectionUtils.isEmpty(list);
        System.out.println(empty3);
        System.out.println("================================");

        boolean empty4 = CollectionUtils.isNotEmpty(null);
        System.out.println(empty4);
        boolean empty5 = CollectionUtils.isNotEmpty(new ArrayList());
        System.out.println(empty5);
        List list1=new ArrayList();
        list1.add("helloworld1");
        list1.add("helloworld2");
        boolean empty6 = CollectionUtils.isNotEmpty(list1);
        System.out.println(empty6);
    }

结果为:

 

 项目中使用:

List<AttachFile> fileList = attachFileService.getFileList(noteObj.getId(), "t_sys_notification", "attach_files");
if (CollectionUtils.isNotEmpty(fileList)) {
noteObj.setAttachFiles(fileList);
}
List<Variety> list = varietyMapper.selectByExample(example);
if (CollectionUtils.isEmpty(list)) {
return Result.operating("查询品种", true, ResultCode.SUCCESS, null);
}

 通过StringUtils工具类判断字符串是否为空

先引入StringUtils工具类:

import org.apache.commons.lang3.StringUtils;

工具类中的部分方法:

public static boolean isEmpty(CharSequence cs) {
return cs == null || cs.length() == 0;
}

public static boolean isNotEmpty(CharSequence cs) {
return !isEmpty(cs);
}

在项目中的应用:

if(StringUtils.isNotEmpty(materialName)){
map.put("materialName", materialName);
}
if (!StringUtils.isEmpty(groupName)) {
argMap.put("groupName", groupName);
}

 

posted on 2020-10-30 16:54  周文豪  阅读(1985)  评论(0编辑  收藏  举报