青春有我
作为 for 循环的替代方法,您可以尝试使用stream api来解决此问题。这个想法是完全一样的:在每个子列表中找到最大元素。使用Comparator在最大元素中查找具有最小元素的子列表。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(); 代码更少,可以说很容易理解代码的意图。您甚至可以使用以下方法缩短代码Comparator::comparing:List.of(List.of(1, 2, 5), List.of(0, 1, 2), List.of(8, 0, 0)) .stream() .min(Comparator.comparing(Collections::max)) .get();让我们更详细地看看这里发生了什么。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]所以执行可能看起来类似于这样: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 iterationfind 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. 希望这个对你有帮助。