How to equalize the size of the list collection Java

I have a collection of lists that contain data from a streamed sensor. I wrote a for loop to form it to the format that I would later use to send it to another place (web server). However, sometimes the size of the lists differs by 1 or 2, and when it does the code will throw an out of bounds exception.

This is the code I use to assemble the format,

for (int i = 0; i < acceleroElaps.size(); i++) {
    HashMap data = new HashMap();
    data.put("person", "Adi");
    data.put("tool", "Accelerometer");
    data.put("time", acceleroTime.get(i));
    data.put("elapsed", acceleroElaps.get(i));
    data.put("xaxis", acceleroXval.get(i));
    data.put("yaxis", acceleroYval.get(i));
    data.put("zaxis", acceleroZval.get(i));


Sometimes one of the lists doesn't have the same size. I've tried to iterate it over with iterator like this

ListIterator<String> iterAT = acceleroTime.listIterator();
ListIterator<String> iterAE = acceleroElaps.listIterator();
ListIterator<String> iterAX = acceleroXval.listIterator();
ListIterator<String> iterAY = acceleroYval.listIterator();
ListIterator<String> iterAZ = acceleroZval.listIterator();

while (iterAT.hasNext() && iterAE.hasNext() && iterAX.hasNext() && iterAY.hasNext() && iterAZ.hasNext()){
    String at =;
    String ae =;
    String ax =;
    String ay =;
    String az =;
    HashMap data = new HashMap();
    data.put("person", "Adi");
    data.put("tool", "Accelerometer");
    data.put("time", at);
    data.put("elapsed", ae);
    data.put("xaxis", ax);
    data.put("yaxis", ay);
    data.put("zaxis", az);

However, this would throw ConcurrentModificationException, so I tried to equalize the size of the lists, because it just differs 1 or 2 data points. Or maybe there's another solution? I'm running out of ideas.


  • I've found a solution, and what I did is create a function to find the smallest list.

    private int theSmallestVal(int a, int b, int c, int d, int e){
        int[] val = {a, b, c, d, e};
        return val[0];

    Then I call the function like this:

    al = theSmallestVal(acceleroTime.size(),acceleroElaps.size(), acceleroXval.size(),
                        acceleroYval.size(), acceleroZval.size());

    After I found the smallest the value, I use that value to be the reference value to be iterated by for i.

    for (int i = 0; i < al; i++) {
         HashMap data = new HashMap();
         data.put("person", "Adi");
         data.put("tool", "Accelerometer");

    By doing so, I could avoid out of bound exception.