Photo by Shahadat Rahman on Unsplash

Introduction

public class Student {
private int age;

private String name;

public int getAge ( ) {
return age;
}

public void setAge ( int age ) {
this.age = age;
}

public String getName ( ) {
return name;
}

public void setName ( String name ) {
this.name = name;
}
}
public class ClassRoom {
private List< Student > students = new ArrayList<> ( );

public List< Student > getStudents ( ) {
return students;
}

public void add ( Student student ) {
this.students.add ( student );
}
}
ClassRoom classRoom = new ClassRoom ( );

for ( int i = 0 ; i < 100 ; i++ ) {
int age = ( int ) ( Math.random ( ) * 20.0 + 1.0 );
String name = "Student" + ( i + 1 );

Student student = new Student ( );
student.setAge ( age );
student.setName ( name );

classRoom.add ( student );
}

ForEach

classRoom.getStudents ( ).stream ( ).forEach ( student ->
System.out.println ( "Name: " + student.getName ( ) + ", Age: " + student.getAge ( ) ) );
Name: Student1, Age: 9
Name: Student2, Age: 14
Name: Student3, Age: 5
Name: Student4, Age: 10
Name: Student5, Age: 16
Name: Student6, Age: 6
Name: Student7, Age: 17
Name: Student8, Age: 16
...

Map

List studentNames = classRoom.getStudents ( ).stream ( )
.map ( student -> student.getName ( ) ).collect ( Collectors.toList ( ) );
studentNames.stream ( ).forEach ( System.out::println );
Student1
Student2
Student3
Student4
Student5
Student6
Student7
Student8
...

Sum

int sum = classRoom.getStudents ( ).stream ( )
.mapToInt ( student -> student.getAge ( ) ).sum ( );
System.out.println ( "Sum of age: " + sum );
Sum of age: 1117

Filter

classRoom.getStudents ( ).stream ( )
.filter ( student -> student.getAge ( ) >= 15 && student.getAge ( ) <= 17 )
.forEach ( student ->
System.out.println ( "Name: " + student.getName ( ) + ", Age: " + student.getAge ( ) ) );
Name: Student5, Age: 16
Name: Student7, Age: 17
Name: Student8, Age: 16
Name: Student18, Age: 15
Name: Student31, Age: 15
Name: Student35, Age: 17
Name: Student39, Age: 17
Name: Student48, Age: 17
Name: Student52, Age: 16
Name: Student53, Age: 17
Name: Student61, Age: 15
Name: Student64, Age: 15
Name: Student73, Age: 16
Name: Student88, Age: 16
Name: Student97, Age: 15

Conclusion

I am a software engineer focusing on Java programming language and Public Key Infrastructure (PKI). Loves Linux and open-source technology.