我有一個 Excel 作業表中單元格的 Arraylist。我想從我實際擁有的單元格陣列串列中創建大小為 50 的子陣列串列,從 1590 的索引開始,以size()-700.
我想從每個子陣列串列中獲取最高數字并將其放入新的陣列串列中。在新的 Arraylist 中應該只有每個 subarraylist 的最高值。
輸入資料是我的單元格串列。
使用這段代碼,我得到了 50 多個數字,但它并不總是最高值。有人有想法嗎?
這是我的代碼:
int partitionSize = 50;
List<List<Cell>> partitions = new ArrayList<>();
List <Cell> high = new ArrayList();
Cell max = data.get(1590);
for (int i = 1590; i < data.size()-700; i = partitionSize) {
partitions.add(data.subList(i, Math.min(i partitionSize, data.size()-700)));
}
for (List<Cell> list : partitions) {
for (int i = 1; i < list.size(); i ) {
if (list.get(i).getNumericCellValue() > max.getNumericCellValue()) {
max = list.get(i);
}
high.add(max);
}
}
uj5u.com熱心網友回復:
磁區串列可以使用IntStream::iterate:
int start = 1590;
int end = data.size() - 700;
int size = 50;
List<List<Cell>> partitions = IntStream
.iterate(start, i -> i < end, i -> i size) // IntStream
.mapToObj(i -> data.subList(i, Math.min(i size, end)))
.collect(Collectors.toList())
;
然后可以檢索具有最大值的單元格串列,如下所示:
List<Cell> maxPerRange = partitions
.stream() // Stream<List<Cell>>
.map(list -> list.stream() // Stream<Cell>
.max(Comparator.comparing(Cell::getNumericCellValue))
.get()
)
.collect(Collectors.toList());
類似地,可以在不顯式拆分子串列中的輸入資料的情況下創建最大值串列,只需使用類似于嵌套回圈的適當范圍:
List<Cell> maxPerRange = IntStream
.iterate(start, i -> i < end, i -> i size) // IntStream
.mapToObj(i -> IntStream.range(i, Math.min(i size, end))
.mapToObj(data::get)
.max(Comparator.comparing(Cell::getNumericCellValue))
.get()
)
.collect(Collectors.toList());
uj5u.com熱心網友回復:
您可以利用 Stream API。
例如:
List<List<Integer>> partitions = new ArrayList<>();
List<Integer> high = partitions.stream()
.map(partition -> partition.stream().max(Integer::compareTo))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/368805.html
