通過CollectionUtils工具類判斷集合是否為空,通過StringUtils工具類判斷字符串是否為空


通過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);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM