In Java, remove empty elements from a list of Strings

前端 未结 11 2411
余生分开走
余生分开走 2020-12-01 06:05

In Java, I have an ArrayList of Strings like:

[,Hi, ,How,are,you]

I want to remove the null and empty elements, how to change it so it is l

11条回答
  •  感情败类
    2020-12-01 06:35

    • This code compiles and runs smoothly.
    • It uses no iterator so more readable.
    • list is your collection.
    • result is filtered form (no null no empty).

    public static void listRemove() {
        List list = Arrays.asList("", "Hi", "", "How", "are", "you");
        List result = new ArrayList();
    
        for (String str : list) {
            if (str != null && !str.isEmpty()) {
                result.add(str);
            }
        }
    
        System.out.println(result);
    }
    

提交回复
热议问题