As an alternative to the for-loop you might try to resolve this issue using stream api. The idea is exactly the same:
- find maximum element in each sublist.
- use Comparator to find sublist with minimum element among maximum elements.
List.of(List.of(1, 2, 5), List.of(0, 1, 2), List.of(8, 0, 0))
.stream()
.min((a, b) ->
a.stream().max(Integer::compare).get()
.compareTo(
b.stream().max(Integer::compare).get()
)
).get();
There is less code it is arguably easily to understand the intention of the code.
You can even make code shorter by using Comparator::comparing method:
List.of(List.of(1, 2, 5), List.of(0, 1, 2), List.of(8, 0, 0))
.stream()
.min(Comparator.comparing(Collections::max))
.get();
Let's have a look at what is going on here in more details.
List.of(List.of(1, 2, 5), List.of(0, 1, 2), List.of(8, 0, 0))
// lets get stream of list Stream<List<Integer>>.
.stream()
// find sublist which has minimum maximum element.
.min((a, b) ->
// a & b are sublist, for example: [1,2,5], [0,1,2]
// find maximum from a [1,2,5] which is [5]
a.stream().max(Integer::compare).get()
// compare maximum from a to maximum from b
.compareTo(
// find maximum from a [0,1,2] which is [2]
b.stream().max(Integer::compare).get()
)
// get minimum out of [5,2]
).get(); // [0, 1, 2]
So the execution might look similar to this:
Initial list is: [1,2,5], [0,1,2], [8, 0, 0]
find minimum list based on maximum:
min( max([1,2,5]), max([0,1,2]))
min( [5], [2])
[2] -> list [0,1,2] contains minimum maximum element so far, go the the next iteration
find minimum list based on maximum:
min( max([0,1,2]), max([8, 0, 0]) )
min( [2], [8])
[2] -> list [0,1,2] contains minimum maximum element so far,
there no other element in the stream, [0,1,2] is final result.
I hope you find this useful.
list? Please create a minimal reproducible example