Артур Антонян Артур Антонян - 29 days ago 12
Android Question

Split array of dates into multiple arrays

For example, i have array with some dates

2016-11-11T12:13:14.120Z

2016-11-12T12:13:14.120Z

2016-11-13T12:13:14.120Z

2016-12-10T12:12:14.120Z

2016-12-10T12:13:14.120Z

2016-12-10T15:13:14.120Z

2016-12-11T12:13:14.120Z

2017-01-11T12:13:14.120Z

i need to achieve something like this :

[[2016-11-11T12:13:14.120Z, 2016-11-12T12:13:14.120Z], [2016-11-13T12:13:14.120Z], [2016-12-10T12:12:14.120Z,2016-12-10T12:13:14.120Z,2016-12-10T15:13:14.120Z, 2016-12-11T12:13:14.120Z], [2017-01-11T12:13:14.120Z]]


if difference between first and n+1 date is less then 24h this dates must be in array, else - create next array and so on.

I can write only something like that

int step = 24;
int currentPos = 0;

ArrayList<ArrayList<Item>> result = new ArrayList<>();
ArrayList<Item> currentArray = new ArrayList<>();

for (int i = 0; i < items.size(); i++) {
Item item = items.get(currentPos);
for (int j = 0; j < items.size(); j++) {
int tmp = currentPos + 1;
if (DateUtils.getDifferenceInHours(item.getEndDate(), items.get(tmp).getEndDate()) <= step) {
currentArray.add(items.get(tmp));
currentPos++;
} else {
currentArray.add(item);
result.add(currentArray);
currentArray = new ArrayList<>();
currentPos++;
break;
}

}
}


But i have indexOutOfBoundsException
Please, help!

Answer

This is a simplified example with integers.I Used a Set to remove the duplicates from the result.

Try this,

// Create sample ArrayList. Don't do this in your actual code.
ArrayList<Integer> items = new ArrayList<Integer>() {
    {
        add(1);
        add(2);
        add(3);
        add(2);
        add(3);
        add(2);                
        add(4);                
    }
};

int step = 24;
Set<ArrayList<Integer>> result = new HashSet<>();       

for (int i = 0; i < items.size(); i++) {
    Integer item1 = items.get(i);
    ArrayList<Integer> currentArray = new ArrayList<>();
    for (int j = 0; j < items.size(); j++) {
        Integer item2 = items.get(j);
        if (item1 == item2) { // This is where you need to find the difference of dates
            currentArray.add(item1);
        }
    }
    result.add(currentArray);
}

System.out.println(result);

Output,

[[4], [1], [3, 3], [2, 2, 2]]