簡體   English   中英

如何從這段代碼中的arrayList中刪除空元素

[英]How to remove empty elements from arrayList in this code

我的代碼遇到問題,無法刪除arrayList中的空元素。 它最終返回[1, 2, 3, 0, 8, , 12 , , 34 , 0 ]但是在多次嘗試之后這些空元素不會被刪除

public static ArrayList<String> readNumbers() {
    Scanner inFile = null;
    File file = null;
    String filePath = (JOptionPane.showInputDialog("Please enter a file path"));
    int size = 0;
    ArrayList<String> result = new ArrayList<String>();

    try {
        file = new File(filePath);
        inFile = new Scanner(file);
        int skippedCounter = 0;

        for(int i = 0; inFile.hasNext(); i++){
            if(inFile.hasNextInt())
                result.add(inFile.next());
            else{
                String strOut = "";
                String data = inFile.nextLine();

                for(int j = 0; j <= data.length() - 1; j++){
                    if(!Character.isLetter(data.charAt(j))){
                        strOut += data.charAt(j);
                    }
                    else
                        skippedCounter++;
                }
                if(!strOut.isEmpty())
                    result.add(strOut);
            }
        }
    } 
    catch (FileNotFoundException e) {
        System.out.println("File not found");
    } 
    catch(NumberFormatException e){
        System.out.println("Not a number");
    }
    finally {
        inFile.close();
    }
    int count = 0;
    result.removeIf(String::isEmpty);

    return result;
}

String::isEmpty()僅檢查字符串的長度是否為零。 如果您的字符串僅包含空格或其他空格,則不會返回true

您可以先執行String.trim() ,然后檢查String.isEmpty()

result.removeIf(s -> s.trim().isEmpty());

我相信在Java 8及更高版本中,您可以執行以下操作從列表中刪除所有空值: results.removeIf(item -> != StringUtils.isEmpty(item));

你可以試試:

List<Integer> listWithNulls = Arrays.asList(1,null, 2, 3, null, 4);

List<Integer> listWithoutNulls = listWithNulls.stream().filter(Objects::nonNull).collect(Collectors.toList());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM