如何根据列表中元素的字节大小创建列表列表?
鉴于我有列表值。我想根据元素的字节大小之和将此列表分为多个列表。
List<List<String>> splitList(List<String> listToSplit, int maxByteSize)
假设我有一个ListlistToSplit = Arrays.asList(“ Value1”,“ Value2”,“ Value3”));
并且maxByteSize = 12。
然后我希望获得2个列表-一个包含Value1和Value2的列表,另一个包含Value3
这是我到目前为止尝试过的
private List<List<String>> splitList( List<String> values, int maxByteSize) {
List<List<String>> returnList = new ArrayList<>();
returnList = buildValuesList(maxByteSize, values.size(), values, returnList);
return returnList;
}
private List<List<String>> buildList(int availableSize, int noOfValues, List<String> values,
List<List<String>> returnList) {
List<String> valuesList = new ArrayList<>();
List<String> remainderValues = new ArrayList<>(values);
returnList.add(valuesList);
int currentSize = 0;
for (String val : values) {
int valueSize = val.getBytes().length;
if (currentSize < availableSize && (currentSize + valueSize < availableSize)) {
currentSize += valueSize;
valuesList.add(val);
remainderValues.remove(val);
} else {
buildValuesList(availableSize, noOfValues, remainderValues, returnList);
}
}
return returnList;
}
答案 0 :(得分:0)
遍历listToSplit,并且如果当前元素的字节长度与先前元素的字节长度之间的总和大于maxByteSize
,则将当前列表添加到列表以返回并重置长度计数器添加到列表中以返回的字符串中的
public List<List<String>> splitList(List<String> listToSplit, int maxByteSize) {
List<List<String>> splittedList = new ArrayList<>();
List<String> currentList = new ArrayList<>();
int currentSize = 0;
for (String in : listToSplit) {
if (currentSize + in.getBytes().length > maxByteSize) {
splittedList.add(currentList);
currentList = new ArrayList<>();
splittedList.add(currentList); // add the new list to the list to return
currentSize = 0;
}
currentSize += in.getBytes().length;
currentList.add(in);
}
return splittedList;
}