0

I experienced a problem with my code where I can not remove empty elements in my arrayList. It ends up returning [1, 2, 3, 0, 8, , 12 , , 34 , 0 ] however those empty elements do not get removed after numerous attempts

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;
}

3 Answers 3

1

String::isEmpty() only checks if the length of the string is zero. It doesn't return true if your string consists of only spaces or other whitespace.

You can do a String.trim() first and then check for String.isEmpty().

result.removeIf(s -> s.trim().isEmpty());
Sign up to request clarification or add additional context in comments.

2 Comments

Hi this fixed it and I appreciate it, what does the -> mean?
It's a lambda. It's short for new Function<String,String>() { public String apply(String s) { return s.trim().isEmpty(); } }, basically.
0

I believe in Java 8 and up, you can do something like this to remove all empty values from list: results.removeIf(item -> != StringUtils.isEmpty(item));

Comments

0

You can try:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.