Skip to content

Instantly share code, notes, and snippets.

@ShabanKamell
Last active September 11, 2018 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShabanKamell/0ec17653034c7c6c9e58f1c189ee9a03 to your computer and use it in GitHub Desktop.
Save ShabanKamell/0ec17653034c7c6c9e58f1c189ee9a03 to your computer and use it in GitHub Desktop.

Java Streams API Example

Java Streams API is so powerful for many reasons:

  1. Help you get rid of many boilerplate.
  2. Functioanl.
  3. Easy to use
  4. Reactive

And there're many reasons. I suggest you read Java 8 in Action

Example:

Data

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)  
);

Get list of students names

The Old Way

List<String> namesOfStudents = new ArrayList<>();  
for (Student student : students)  
    namesOfStudents.add(student.getName()); 

The New Way

List<String> namesOfStudents = students  
        .stream()  
        .map(Student::getName)  
        .collect(Collectors.toList());  

Filter By Age

The Old Way

List<Student> studentsFilteredByAge = new ArrayList<>();  
for (Student student : students){  
    if(student.age > 10)  
        studentsFilteredByAge.add(student);  
}

The New Way

List<Student> studentsFilteredByAge =
            Stream.of(students)  
               .filter(student -> student.getAge() > 10)  
               .toList();

Let's Compose It

List<String> namesOfStudentsGreaterThan10 =
            Stream.of(students)  
               .filter(student -> student.getAge() > 10)
               .map(Student::getName)  
               .toList();

You can compose any number of operator as you want

Can i use Streams API in Android?

Yes, starting form SDK 24 you can use Streams API.

Can i use Streams API in Android before SDK 24?

Yes, there're many libraries help you do this. My best library is aNNiMON's Lightweight-Stream-API

License

Apache license 2.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment