java - 基于线性键中的间隙分离数组
问题描述
我希望根据键中的间隙将单个数组分成单独的数组。例如采取这种情况:
我正在尝试为每月的连续几天创建单独的数据集(数组)。如果错过了一天,则需要从具有值的第二天开始创建新的数据集。
数据在一个数组中检索,如下所示:
[1:10, 2:8, 4:5, 5:12, 8:6, 9:10, 10:5, 11:4, 13:6, 14:5]
我想输出:
[1:10, 2:8], [4:5, 5:12], [8:6, 9:10, 10:5, 11:4], [13:6, 14:5]
我将如何实现这一目标?
我目前有这个:
ArrayList<Entry> allValues = new ArrayList<>();
// Data Retrieval from the Server is Here (hidden for privacy)
// Each data entry contains key and value
// This is converted into a data model "Entry" which is essentially an x & y coordinate ( Entry(x,y) )
// and then added to the allValues List
List<ArrayList<Entry>> rawDataSets = new ArrayList<>();
ArrayList<Entry> tempDataSet = new ArrayList<>();
for(int i = 0; i < allValues.size(); i++){
Entry tempEntry = allValues.get(i);
if(i == tempEntry.getX()){
tempDataSet.add(tempEntry);
}else{
if(tempDataSet.size() > 0) {
rawDataSets.add(tempDataSet);
tempDataSet.clear();
}
}
}
解决方案
这样的事情应该可以解决问题:
ArrayList<Entry> allValues = new ArrayList<>();
// Assuming at this point that `allValues` is sorted in ascending order by X values.
// If necessary, it can be sorted with
//
// Collections.sort(allValues, Comparator.comparing(Entry::getX));
//
List<ArrayList<Entry>> rawDataSets = new ArrayList<>();
ArrayList<Entry> tempDataSet = new ArrayList<>();
for (Entry tempEntry : allValues){
if (!tempDataSet.isEmpty() &&
tempEntry.getX() != tempDataSet.get(tempDataSet.size()-1).getX() + 1)
{
// tempDataSet is not empty, and tempEntry's X is not
// consecutive with the X of tempDataSet's last entry, so it's
// it's time finish with the current tempDataSet and start fresh
// with a new one.
rawDataSets.add(tempDataSet);
tempDataSet = new ArrayList<>();
}
// Regardless of what happened, or didn't happen, with tempDataSet above,
// the current allValues entry now belongs with the current tempDataSet
tempDataSet.add(tempEntry);
}
// Now add any final non-empty tempDataSet (there will always be one if
// allValues wasn't empty) onto rawDataSets
if (!tempDataSet.isEmpty()) {
rawDataSets.add(tempDataSet);
}
推荐阅读
- c# - 更新列表中的属性字段
- perl - 如何执行模板takelit脚本?
- android - 在片段中绑定 MediaProjection 服务会导致配置更改出现安全异常
- c# - C# 剪贴板和 DataObject 未按预期运行
- python - 如何在 Python 中编写正则表达式以删除字符串中间数字的前导零
- generics - 如何创建一个采用 u32 或 &str 并分别返回 u32 或 usize 的闭包?
- python - 用列中的混合字符替换特定字符串
- python - Pandas Dataframe groupby 重叠
- python - 我在 vsc 和 windows 10 中的烧瓶中创建数据库时遇到问题。有人可以帮助解决这个问题吗?
- c# - 如何正确调整 Datagrid 的大小以打印 C# 表单