Java Reference
In-Depth Information
The following snippet of code prints the details of females in the person list:
Person.persons()
.stream()
.filter(Person::isFemale)
.forEach(System.out::println);
(3, Donna, FEMALE, 1962-07-29, 8700.00)
(5, Laynie, FEMALE, 2012-12-13, 0.00)
The program in Listing 13-6 shows how to use the forEach() method to increase the income of all females by 10%.
The output shows that only Donna got an increase because another female named Laynie had 0.0 income before.
Listing 13-6. Applying the ForEach Operation on a List of Persons
// ForEachTest.java
package com.jdojo.streams;
import java.util.List;
public class ForEachTest {
public static void main(String[] args) {
// Get the list of persons
List<Person> persons = Person.persons();
// Print the list
System.out.println("Before increasing the income: " + persons);
// Increase the income of females by 10%
persons.stream()
.filter(Person::isFemale)
.forEach(p -> p.setIncome(p.getIncome() * 1.10));
// Print the list again
System.out.println("After increasing the income: " + persons);
}
}
Before increasing the income: [(1, Ken, MALE, 1970-05-04, 6000.00), (2, Jeff, MALE, 1970-07-15,
7100.00), (3, Donna, FEMALE, 1962-07-29, 8700.00), (4, Chris, MALE, 1993-12-16, 1800.00),
(5, Laynie, FEMALE, 2012-12-13, 0.00), (6, Li, MALE, 2001-05-09, 2400.00)]
After increasing the income: [(1, Ken, MALE, 1970-05-04, 6000.00), (2, Jeff, MALE, 1970-07-15,
7100.00), (3, Donna, FEMALE, 1962-07-29, 9570.00), (4, Chris, MALE, 1993-12-16, 1800.00),
(5, Laynie, FEMALE, 2012-12-13, 0.00), (6, Li, MALE, 2001-05-09, 2400.00)]
Applying the Map Operation
A map operation (also known as mapping) applies a function to each element of the input stream to produce another
stream (also called an output stream or a mapped stream). The number of elements in the input and output streams is
the same. The operation does not modify the elements of the input stream (at least it is not supposed to).
 
Search WWH ::




Custom Search