Remove all null or empty strings in an array. - Android java.lang

Android examples for java.lang:Array Element

Description

Remove all null or empty strings in an array.

Demo Code


//package com.java2s;
import android.text.TextUtils;

import java.util.ArrayList;

public class Main {
    /**//ww  w  .ja  v  a  2 s .c  o  m
     * Remove all null or empty strings in an array.
     * 
     * @param array the array to normalize. If you pass {@code null}, an empty
     *            array will be returned.
     */
    public static final String[] normalize(String[] array) {
        if (null == array) {
            return new String[0];
        }
        final int length = array.length;
        final ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < length; i++) {
            final String item = array[i];
            if (!TextUtils.isEmpty(item) && !TextUtils.isEmpty(item.trim())) {
                list.add(item);
            }
        }
        String[] normalizedItems = new String[list.size()];
        normalizedItems = list.toArray(normalizedItems);
        return normalizedItems;
    }
}

Related Tutorials