-2

So i currently have :

List<String> lineList = new ArrayList<String>();
String thisLine = reader.readLine();

while (thisLine != null) {
    lineList.add(thisLine);
    thisLine = reader.readLine();
}
System.out.println(lineList);

Which basically is reading a text file and returning the numbers in the text file. The output im getting is [0 6 13 0 0 75 33 0 0 0 4 29 21 0 86 0 32 66 0 0] which seems to be correct. However what I have to do is remove all the zeros without creating a new array. But will i have to convert this string arraylist to an integer array list to be able to do so? How could I only remove the zeros? Thanks!

blackpanther
  • 10,998
  • 11
  • 48
  • 78
user2778618
  • 27
  • 1
  • 7

4 Answers4

4

use removeAll() method to remove all zeros from an ArrayList...

lineList.removeAll(Collections.singleton(0));

Jay Patel
  • 2,341
  • 2
  • 22
  • 43
3

You just need to modify your while loop like this:

 while (thisLine != null) {
       if(!thisLine.trim().equals("0")) {
           lineList.add(thisLine);
       }
        thisLine = reader.readLine();
    }

EDIT:

As per your input above code will not work as you are getting everything in a single line. You should use a Scanner to read it like this:

Scanner s = new Scanner(new File(<your file path>));
 List<Integer> lineList = new ArrayList<Integer>();

while(s.hasNextInt()){
    int i = s.nextInt();
     if(i!=0) {
         lineList.add(i);
     }
}

Hope this helps.

Sanjeev
  • 9,876
  • 2
  • 22
  • 33
0

I'd to it in the while loop:

while (thisLine != null) {
    if(!thisLine.equals("0"){
        lineList.add(thisLine);
    }
    thisLine = reader.readLine();
}
Toon Borgers
  • 3,638
  • 1
  • 14
  • 22
0

Probably something like this would be sufficient ?

for(Iterator<String> it=lineList.iterator(); it.hasNext();) {
    String str = it.next();
    if(str.equalsIgnoreCase("0")) {
        it.remove();   
    }
}