Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Print a list without all the empty elements of the list

I would like to know if there is a fast way to print all the not empty elements of a string list in Java.

Currently, this is my code and it works, but I would like to know if there is another, shorter way to do it. That means without creating a "cloned list" from which we removed all the empty element (as we must not edit the original list "strings")

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");

//get count of empty string
int countEmptyStr = (int) strings.stream().filter(string -> string.isEmpty()).count();
System.out.println("Number of empty strings:" + countEmptyStr );
//get count of no empty string
int countNoEmptyStr = (int) strings.stream().filter(string -> !string.isEmpty()).count();
System.out.println("Number of no-empty strings:" + countNoEmptyStr );
//print only no empty string from the list
List<String> stringsRmvd = new ArrayList<String>(strings);
stringsRmvd.removeAll(Arrays.asList("", null));
System.out.println("Print only no empty string from the list:" + stringsRmvd);

And we get in the output (as expected):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Number of empty strings:2
Number of no-empty strings:5
Print only no empty string from the list:[abc, bc, efg, abcd, jkl]

>Solution :

Filter out empty strings and print the remained elements:

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
        
strings.stream()
    .filter(str -> !str.isEmpty()) // retain the string that matches the predicate (i.e. not empty)
    .forEach(System.out::println);

Output:

abc
bc
efg
abcd
jkl
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading