Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Max of Multiple Lists

I'm pretty new to java streams and am trying to determine how to find the max from each list, in a list of lists, and end with a single list that contains the max from each sublist.

I can accomplish this by using a for loop and stream like so:

// databaseRecordsLists is a List<List<DatabaseRecord>>

List<DatabaseRecord> mostRecentRecords = new ArrayList<>();

for (List<DatabaseRecord> databaseRecords : databaseRecordsLists) {
            mostRecentRecords.add(databaseRecords.stream()
                    .max(Comparator.comparing(DatabaseRecord::getTimestamp))
                    .orElseThrow(NoSuchElementException::new));
        }

I've looked into the flatMap api, but then I'll only end up with a single map of all DatabaseRecord objects, where I need a max from each individual list.

Any ideas on a cleaner way to accomplish this?

like image 686
jtb07 Avatar asked Mar 02 '23 13:03

jtb07


1 Answers

You don't need flatMap. Create a Stream<List<DatabaseRecord>>, and map each List<DatabaseRecord> of the Stream to the max element. Then collect all the max elements into the output List.

List<DatabaseRecord> mostRecentRecords =
    databaseRecordsLists.stream()
                        .map(list -> list.stream()
                                         .max(Comparator.comparing(DatabaseRecord::getTimestamp))
                                         .orElseThrow(NoSuchElementException::new))
                        .collect(Collectors.toList());
like image 181
Eran Avatar answered Mar 05 '23 15:03

Eran