remove Empty element in String array - Java Collection Framework

Java examples for Collection Framework:Array Join

Description

remove Empty element in String array

Demo Code


//package com.java2s;

import java.util.ArrayList;

import java.util.List;

public class Main {
    public static void main(String[] argv) throws Exception {
        String[] origArray = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        System.out.println(java.util.Arrays
                .toString(removeEmpty(origArray)));
    }//from w  w w. j av  a2  s .c o m

    public static String[] removeEmpty(String[] origArray) {
        List<String> newArr = new ArrayList<String>();
        for (String el : origArray) {
            if (hasText(el)) {
                newArr.add(el);
            }
        }
        return newArr.toArray(new String[newArr.size()]);
    }

    public static boolean hasText(String str) {
        return null != str && !"".equals(str.trim());
    }
}

Related Tutorials