- Help you get rid of many boilerplate.
- Functioanl.
- Easy to use
- Reactive
And there're many reasons. I suggest you read Java 8 in Action
Example:
class Student {
private String name;
private int age;
public String getName() {
return name;
}
public Student setName(String name) {
this.name = name;
return this; }
public int getAge() {
return age;
}
public Student setAge(int age) {
this.age = age;
return this; }
}
List<Student> students = Arrays.asList(
new Student().setName("Student 1").setAge(13),
new Student().setName("Student 2").setAge(12),
new Student().setName("Student 3").setAge(16),
new Student().setName("Student 4").setAge(9),
new Student().setName("Student 5").setAge(7)
);
List<String> namesOfStudents = new ArrayList<>();
for (Student student : students)
namesOfStudents.add(student.getName());
List<String> namesOfStudents = students
.stream()
.map(Student::getName)
.collect(Collectors.toList());
List<Student> studentsFilteredByAge = new ArrayList<>();
for (Student student : students){
if(student.age > 10)
studentsFilteredByAge.add(student);
}
List<Student> studentsFilteredByAge =
Stream.of(students)
.filter(student -> student.getAge() > 10)
.toList();
List<String> namesOfStudentsGreaterThan10 =
Stream.of(students)
.filter(student -> student.getAge() > 10)
.map(Student::getName)
.toList();
Yes, starting form SDK 24 you can use Streams API.
Yes, there're many libraries help you do this. My best library is aNNiMON's Lightweight-Stream-API