List <Person> roster = new List<Person>();
Integer totalAgeReduce = roster
.stream()
.map(Person::getAge)
.reduce(
0,
(a, b) -> a + b);
Can anyone help me understand the above code snippet. My understanding is that the stream method will first iterate through the entire roster List and while it is iterating it will create a new List of the mapped objects with every person's age in it. Then it will finally call the reduce after the mapping is done (the reduce is only called at the end after mapping correct?). And in the reduce it starts of at 0, and in the first iteration of reduce on the newly mapped list a = 0 and b is equal to the first element in the List that was created from the mapping function. Then it will continue and add all the elements from the mapped list and return to you an integer with the sum of all the ages.
rosterthe same as thelvariable? --- 2)stream()andmap()do not "create" new lists. Logically you might think that way, but a better way to think of it is a pipeline.stream()sends the elements down a pipe. At a junction in the pipe,mapstrips the age out of the object and sends that down the pipe instead of the original object.reduce()then compresses all the ages into a single value, as defined by the supplied lambda.int totalAge = roster.stream().mapToInt(Person::getAge).sum();