I have a list of list of integers as below:
List<List<Integer>> integers = Arrays.asList(
Arrays.asList(8, 9, 4, 5, 6), // sum is 32
Arrays.asList(10, 0, 6, 3, 7), //sum is 26
Arrays.asList(1, 9, 2, 16, 3开发者_如何学编程), //sum is 31
Arrays.asList(2, 22, 4, 5), //sum is 33
Arrays.asList(15, 6)); //sum is 21
I need to return max 3 sums calculated from each nested list using stream API. As given above I need to return list containing 33,32,31.
I tried with few stream methods but always gets syntax error. Please help on how to achieve desire result.
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class TopThree {
public static void main(String args[]) {
List<List<Integer>> integers = List.of(List.of( 8, 9, 4, 5, 6),
List.of(10, 0, 6, 3, 7),
List.of( 1, 9, 2, 16, 3),
List.of( 2, 22, 4, 5),
List.of(15, 6));
List<Integer> top3 = integers.stream()
.map(l -> l.stream().reduce(0, Integer::sum))
.collect(Collectors.toList())
.stream()
.sorted(Comparator.reverseOrder())
.limit(3L)
.collect(Collectors.toList());
System.out.println(top3);
}
}
- The first
stream
method returns a stream where every element has typeList<Integer>
. - The
map
method gets the sum of the elements in each [inner] list. - The first
collect
creates a singleList<Integer>
where every element is the sum of one of the [inner]List
s ofintegers
. - This list [of sums] is sorted in descending order.
- Method
limit
takes only the first three elements of the list [of sums]. - The last
collect
creates aList<Integer>
containing the top three sums (as requested).
精彩评论