Remove Null Value from String array in java

前端 未结 8 648
囚心锁ツ
囚心锁ツ 2020-11-29 08:16

How to remove null value from String array in java?

String[] firstArray = {\"test1\",\"\",\"test2\",\"test4\",\"\"};

I need the \"firstArra

8条回答
  •  萌比男神i
    2020-11-29 08:43

    If you want to avoid fencepost errors and avoid moving and deleting items in an array, here is a somewhat verbose solution that uses List:

    import java.util.ArrayList;
    import java.util.List;
    
    public class RemoveNullValue {
      public static void main( String args[] ) {
        String[] firstArray = {"test1", "", "test2", "test4", "", null};
    
        List list = new ArrayList();
    
        for(String s : firstArray) {
           if(s != null && s.length() > 0) {
              list.add(s);
           }
        }
    
        firstArray = list.toArray(new String[list.size()]);
      }
    }
    

    Added null to show the difference between an empty String instance ("") and null.

    Since this answer is around 4.5 years old, I'm adding a Java 8 example:

    import java.util.Arrays;
    import java.util.stream.Collectors;
    
    public class RemoveNullValue {
        public static void main( String args[] ) {
            String[] firstArray = {"test1", "", "test2", "test4", "", null};
    
            firstArray = Arrays.stream(firstArray)
                         .filter(s -> (s != null && s.length() > 0))
                         .toArray(String[]::new);    
    
        }
    }
    

提交回复
热议问题