How to remove trailing nulls (0) from byte ArrayList in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static List<Byte> removeTrailingNulls(List<Byte> byteList) {
        while (!byteList.isEmpty() && byteList.get(byteList.size() - 1) == 0) {
            byteList.remove(byteList.size() - 1);
        }
        
        return byteList;
    }

    public static void main(String[] args) {
        List<Byte> byteList = new ArrayList<>();
        byteList.add((byte) 1);
        byteList.add((byte) 2);
        byteList.add((byte) 3);
        byteList.add((byte) 0);
        byteList.add((byte) 0);
        byteList.add((byte) 0);
        byteList.add((byte) 0);

        List<Byte> trimmedList = removeTrailingNulls(byteList);

        for (Byte b : trimmedList) {
            System.out.print(b + " ");
        }
    }
}


/*
run:

1 2 3 

*/

 



answered Mar 13, 2025 by avibootz

Related questions

2 answers 110 views
1 answer 146 views
1 answer 105 views
2 answers 107 views
1 answer 96 views
1 answer 106 views
1 answer 87 views
...