StreamDemo.java
Download StreamDemo.java
1: import java.util.*;
2: import java.util.stream.*;
3:
4: /** StreamDemo is a trivial example of using Java 8 aggregation operations.
5: * Here, we process a list of Persons, displaying some information on some
6: * and averaging all of their ages at the end.
7: * Written 7/2014
8: * @Author Wayne Pollock, Tampa Florida USA
9: */
10: public class StreamDemo {
11: public static void main ( String [] args ) {
12: List<Person> myList = new ArrayList<>();
13: myList.add( new Person( "Wayne", 56, 'M' ) );
14: myList.add( new Person( "Jane", 17, 'F' ) );
15: myList.add( new Person( "Hymie", 22, 'M' ) );
16: double average = myList.stream()
17: .map( e -> { if (e.getAge() >= 18 )
18: System.out.println( e.getName() );
19: return e;
20: } )
21: .mapToInt( Person::getAge )
22: .average().getAsDouble();
23: System.out.printf( "Average age: %4.2f%n", average );
24: }
25: }
26:
27: /** Trivial class Person
28: */
29: class Person {
30: private String name;
31: private int age;
32: private char gender;
33:
34: public Person ( String name, int age, char gender ) {
35: this.name = name;
36: this.age = age;
37: this.gender = gender;
38: }
39:
40: public String getName () { return name; }
41: public void setName ( int age ) { this.name = name; }
42:
43: public int getAge () { return age; }
44: public void setAge ( int age ) { this.age = age; }
45:
46: public char getGender () { return gender; }
47: public void setGender ( char gender ) { this.gender = gender; }
48: public boolean isMale () { return gender == 'M'; }
49: public boolean isFemale () { return gender == 'F'; }
50: }