我有一个对象列表。我想根据文件大小从arraylist制作子列表。
示例:
[{
"name": "food_image1.jpeg",
"fileSize": 10
},
{
"name": "food_image2.jpeg",
"fileSize": 20
},
{
"name": "food_image3.jpeg",
"fileSize": 30
},
{
"name": "food_image4.jpeg",
"fileSize": 10
}
]
我的固定尺寸是:40;
所以我的子列表将是:
[
[{
"name": "food_image1.jpeg",
"fileSize": 10
},
{
"name": "food_image2.jpeg",
"fileSize": 20
},
{
"name": "food_image4.jpeg",
"fileSize": 10
}
],
[{
"name": "food_image3.jpeg",
"fileSize": 30
}]
]
所以,我有mojo对象 FileInfo.java 有两个属性
public class FileInfo{
private String name;
private Long fileSize;
//setter and getters
}
我的逻辑是:
public List<List<FileInfo>> getAllSublistFromList(){
//fixed size data
long fixedPartSize =40;
long tempSize = 0;
long finalSize = 0;
//here I am fetching all the list
List<FileInfo> fileInfoList = jsondataList();
List<FileInfo> makeSublist = new ArrayList<>();
//Initializing list of DriveFileInfo object within a list.
List<List<FileInfo>> allDataAspart = new ArrayList<>();
//iterating arraylist of DriveFileInfo object
for (int i = fileInfoList.size() - 1; i >= 0; i--) {
//first fetching filesize of every DriveFileInfo object
tempSize = fileInfoList.get(i).getFileSize();
//checking if the file exist or not
if (tempSize >= 1) {
//if the file exist keep it as finalSize.
finalSize = finalSize + tempSize;
//now checking new size is greater than fixed size or not.
if (finalSize <= fixedPartSize) {
//if the finalSize is lessar than fixedSize then add to ArrayList,named makeSublist
makeSublist.add(fileInfoList.get(i));
//after adding to the list remove index from makeSublist Arraylist
fileInfoList.remove(i);
} else {
finalSize = 0;
//if the finalSize is greater than fixedSize then add to ArrayList of Arraylist,named allDataAspart
allDataAspart.add(makeSublist);
//and clean the arraylist means initialize makeSublist arraylist data
makeSublist = new ArrayList<>();
}
}
//checking if the file not exist
else {
//remove the index from fileInfoList arraylist
fileInfoList.remove(i);
}
}
allDataAspart.add(makeSublist);
//returning the arraylist of List object data.
return allDataAspart;
}
但是我没有从列表中获得正确的列表..当列表很长并且固定大小发生变化时,有些文件丢失..请帮助我们..
答案 0 :(得分:0)
这个怎么样:
public List<List<FileInfo>> partition(List<FileInfo> list, int maxSize) {
List<List<FileInfo>> result = new ArrayList<>();
List<FileInfo> current = new ArrayList<>();
int currentSize = 0;
for (FileInfo fi: list) {
if (fi.getFileSize() > 0) {
if (!current.isEmpty()
&& currentSize + fi.getFileSize() > maxSize) {
result.add(current);
current = new ArrayList<>();
currentSize = 0;
}
current.add(fi);
currentSize += fi.getFileSize();
}
}
if (!current.isEmpty()) {
result.add(current);
}
return result;
}