创建并查找子数组列表中的最高值



我有一个Excel工作表中的单元格数组列表。我想从我实际拥有的单元格数组列表中创建大小为50的子数组列表,从1590的索引开始,以size()-700结束。

我想从每个子数组列表中得到最高的数字,并将其放入新的数组列表中。在新的数组列表中,应该只有每个子数组列表的最高值。

输入数据是我的单元格数组。

有了这个代码,我得到了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);
}
}

分区列表可以使用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());

您可以利用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());

最新更新