Java | Delete empty string from list or array

Author - Webner
public class deleteEmptyStringQuick
{
	public static void main(String[] args) 
        {
 	String[] emptyStringArray={"test","test1","","test3","","test4"};
        ArrayList arrayListOfEmptyString=(ArrayList) Arrays.asList(emptyStringArray);

		//normally we will do this
		ArrayList filteredList = new ArrayList();
		for(String string: arrayListOfEmptyString)
                {
			if(!string.isEmpty())
                        {
				filteredList.add(string);
			}
		}
		
//You can achieve this with single line as well: 
filteredList = arrayListOfEmptyString.stream().filter(string >!string.isEmpty()).collect(Collectors.toList());
	}
}

In above code, you can see two different ways to delete empty strings from an array or a list. Normally we use loop to delete empty string from array list or array, but Java 8 has new ways to achieve these things. Now, we use single line code to achieve this.

Webner Solutions is a Software Development company focused on developing CRM apps (Salesforce, Zoho), LMS Apps (Moodle/Totara), Websites and Mobile apps. If you need Web development or any other software development assistance please contact us at webdevelopment@webners.com

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *