例如,我有一些日期
的数组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
我需要实现这样的目标:
[[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]]
如果第一个和第n + 1个日期之间的差异小于24小时,则此日期必须在数组中,否则 - 创建下一个数组,依此类推。
我只能写那样的东西
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;
}
}
}
但我有indexOutOfBoundsException 请帮助!
答案 0 :(得分:0)
将您的代码更改为:
default
答案 1 :(得分:0)
这是一个带整数的简化示例。我使用Set
从结果中删除重复项。
试试这个,
// 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);
输出,
[[4], [1], [3, 3], [2, 2, 2]]