在平時的開發中,基本上都會用到字符串判斷空值和集合判斷空值的處理,還記得在剛乾開發的時候,寫的代碼在如今看起來是真的有點Hello World,那麼此次分享兩個很是經常使用的方法,字符串非空判斷和集合非空判斷。程序員
你有沒見過下面的代碼,要是沒見過你就不配是一個程序員,我還寫過呢!如今回過頭來看感受本身當年真的是太年輕了。apache
public static void main(String[] args) { String str = "bingfeng"; if (str == null || str.equals("")) { } } 複製代碼
那麼經歷同事的各類嫌棄以後,如今終於不這麼寫了,要是如今看到那個初級工程師這麼寫,確定叫兄弟過去欺負他。安全
除了這種寫法以外,也見到過有些人願意本身去實現封裝一層,寫一個工具類用,其實真的感受不必,切莫重複早輪子。這種東西別人已經幫咱們作好了,並且也比咱們這些菜鳥作的好多了,因此推薦直接用就好了。app
咱們直接引入pom文件便可,他給咱們提供了一些基礎的功能供咱們使用。工具
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency> 複製代碼
首先第一種,isNotEmpty 這個方法能夠判斷字符串是否爲空。 第二種,isNotBlank 這個方法也是用來判斷字符串是否爲空。code
public static void main(String[] args) { String str = "bingfeng"; if (StringUtils.isNotBlank(str)) { System.out.println("isNotBlank:" + str); } if (StringUtils.isNotEmpty(str)) { System.out.println("isNotEmpty:" + str); } } 複製代碼
既然上面兩種方法均可以判斷時候爲空,那又有什麼區別呢?首先兩個方法均可以判斷字符串是否爲null,可是咱們日常在業務中,特別是用戶搜索,用戶極可能輸入空白字符,若是用戶什麼也沒輸入,就敲了兩個空格,那麼提交到後臺,按道理來講空字符串確定是不合法的,那麼此時的isNotEmpty是沒法判斷的,相反isNotBlank卻能夠在去除字符串兩邊的空格而後再進行判斷,因此這裏推薦你們使用 isNotBlank 更爲安全。ip
再來看一段當年的傳奇之做開發
public static void main(String[] args) { List<String> list = new ArrayList<>(); if (list == null || list.size() <= 0) { } } 複製代碼
通常對集合都要進行兩項判斷,首先判斷是否不爲null,其次判斷是否不爲爲空,若是都知足,再進行下面的操做,咱們用上面的寫法雖然說沒什麼問題,可是真的有點太年輕了。字符串
推薦寫法:it
public static void main(String[] args) { List<String> list = new ArrayList<>(); if (CollectionUtils.isEmpty(list)) { } } 複製代碼
咱們來看下這個方法的底層實現,便會長大許多。
public static boolean isEmpty(@Nullable Collection<?> collection) { return collection == null || collection.isEmpty(); } 複製代碼
寫到這裏,基本上就差很少啦,可是仍是透露一下我經常使用的祕籍,我通常都會對判斷集合的方式,作一層包裝作成一個工具類,提供更多的方法提升代碼的複用性。你們且看下面。
/** * @Description: TODO <集合工具類> * @Date: 2019/10/15/015 09:32 * @Author: bingfeng */ public class ArrayUtil { /** * 判斷集合是否爲空 * * @param collection * @return */ public static boolean isEmpty(Collection<?> collection) { return CollectionUtils.isEmpty(collection); } /** * 將集合中的元素輸出爲字符串,並用{@code separator}鏈接 * * @param collection * @param separator * @return */ public static String join(Collection<?> collection, String separator) { if (isEmpty(collection)) { return null; } StringBuffer sb = new StringBuffer(); for (Object o : collection) { sb.append(o).append(separator); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } /** * 建立一個空的集合 * * @return */ public static <T> List<T> emptyList() { return Collections.emptyList(); } /** * 將字符串按特定字符分割 * * @param str * @param separator * @return */ public static List<String> transition(String str, String separator) { if (StringUtils.isBlank(str)) { return emptyList(); } String[] split = str.split(separator); return Arrays.asList(split); } } 複製代碼
道阻且長,就讓咱們恩恩愛愛,活得瀟瀟灑灑吧。。。