Skip to content
Advertisement

Create and find highest value in subarraylist

I have an Arraylist of the Cells from an Excel sheet. I want to create subarraylists of size 50 from the Arraylist of Cells I actually have, beginning from the index of 1590 and ending with size()-700.

I want to get the highest number from every subarraylist and put it in the new Arraylist. in the new Arraylist there should be only the highest values of each subarraylist.

Input data is my Arraylist of Cells.

With this code I get more than 50 numbers and it’s not always the highest value. Has anyone an idea?

This is my code:

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);
    }
}

Advertisement

Answer

You could take advantage of the Stream API.

For example:

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());
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement