Home > Software engineering >  Print a list without all the empty elements of the list
Print a list without all the empty elements of the list

Time:12-03

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):

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

CodePudding user response:

You're already using filter, why not use that?

filter(string -> !string.isEmpty()).toList()

For example (not tested):

System.out.println( "Print only non-empty string from the list:" 
      strings.stream()
    .filter(string -> !string.isEmpty())
    .toList() );

CodePudding user response:

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
  • Related