Java 8 Streams

One of the features of Java 8 and best practices is the use of streams.

In this tutorial, we’ll see how to use the Stream.filter() method when we work with Streams in Java.

The filter() method is an intermediate operation of the Stream interface that allows us to filter elements of a stream that match a given Predicate: A common use case of the filter() method is processing collections.

We shall demonstrate a sample in this tutorial.

First: we create a Student class. Each student will have a name, gender, age and a list of courses of which he is enrolled into. We also create Gender and Course enums.

enum Gender {MALE, FEMALE}
enum Course {DATA_STRUCTURES, DATABASE, JAVA, OPERATING_SYSTEMS, NETWORKS, OBJECT_ORIENTED_PROGRAMMING, DOTNET, C}
class Student {
    private String name;
    private int age;
    private Gender gender;
    private List<Course> courses = new ArrayList<Course>();
    public Student(String name, int age, Gender gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Gender getGender() {
        return gender;
    }
    public void setGender(Gender gender) {
        this.gender = gender;
    }
    public List<Course> getCourses() {
        return courses;
    }
    public void setCourses(List<Course> courses) {
        this.courses = courses;
    }
    @Override
    public String toString() {
        return “Student [name=” + name + “, age=” + age + “, gender=” + gender + “, courses=” + courses + “]”;
    }
}

Second: We created a list with some student classes and fill them up with data.

        List<Student> allStudents = new ArrayList<Student>();
        Student s1 = new Student(“Linda”, 18, Gender.FEMALE);
        s1.getCourses().add(Course.DATA_STRUCTURES);
        s1.getCourses().add(Course.DATABASE);
        s1.getCourses().add(Course.OBJECT_ORIENTED_PROGRAMMING);
        s1.getCourses().add(Course.NETWORKS);
        allStudents.add(s1);
        Student s2 = new Student(“Mary”, 20, Gender.FEMALE);
        s2.getCourses().add(Course.DATA_STRUCTURES);
        s2.getCourses().add(Course.JAVA);
        s2.getCourses().add(Course.OPERATING_SYSTEMS);
        s2.getCourses().add(Course.C);
        allStudents.add(s2);
        Student s3 = new Student(“Tina”, 21, Gender.FEMALE);
        s3.getCourses().add(Course.OBJECT_ORIENTED_PROGRAMMING);
        s3.getCourses().add(Course.JAVA);
        s3.getCourses().add(Course.OPERATING_SYSTEMS);
        s3.getCourses().add(Course.NETWORKS);
        allStudents.add(s3);
        Student s4 = new Student(“Antonio”, 18, Gender.MALE);
        s4.getCourses().add(Course.JAVA);
        s4.getCourses().add(Course.OPERATING_SYSTEMS);
        s4.getCourses().add(Course.NETWORKS);
        s4.getCourses().add(Course.DATABASE);
        allStudents.add(s4);
        Student s5 = new Student(“Ahmed”, 20, Gender.MALE);
        s5.getCourses().add(Course.DOTNET);
        s5.getCourses().add(Course.DATA_STRUCTURES);
        s5.getCourses().add(Course.OPERATING_SYSTEMS);
        s5.getCourses().add(Course.DATABASE);
        allStudents.add(s5);

Third: Let’s use filters on the students list. To do that, we can use a lambda expression:

1- We filter all students of age below 20 years.

List<Student> students1 = allStudents.stream().filter(s -> s.getAge() < 20).collect(Collectors.toList());

2- We filter to find one student that is below 20 yrs and male.

Student student = allStudents.stream().filter(s -> s.getAge() < 20 && Gender.MALE.equals(s.getGender())).findAny().orElse(null);

3- We find all students that are female and taking Java course.

List<Student> students2 = allStudents.stream().filter(s -> Gender.FEMALE.equals(s.getGender()) && s.getCourses().stream().anyMatch(c -> Course.JAVA.equals(c))).collect(Collectors.toList());

Iterating over maps in Java

       A Map is a popular Java collection that is used to store key/value pairs. In many situations we are going to need to iterate over the map to display its contents or do some manipulations.

One way to iterate over a map is by using the Map.entrySet() method, which returns a collection-view of the map.

The latter collection elements are of Map.Entry class, we are able to get key and value using getKey() and getValue() methods.

The only way to obtain a reference to a map entry is from the iterator of this collection-view.

       In this post we are going to go over 3 ways to iterate over the map entry using iterator, for loop and lambda expressions.

First let us create a map and give it keys for months of the year with values of how many days are in this month.

        Map<String, String> months = new LinkedHashMap<String, String>();
        months.put(“January”, “31 days”);
        months.put(“February”, “28 days in a common year and 29 days in leap years”);
        months.put(“March”, “31 days”);
        months.put(“April”, “30 days”);
        months.put(“May”, “31 days”);
        months.put(“June”, “30 days”);
        months.put(“July”, “31 days”);
        months.put(“August”, “31 days”);
        months.put(“September”, “30 days”);
        months.put(“October”, “31 days”);
        months.put(“November”, “30 days”);
        months.put(“December”, “31 days”);

1- Iterator

By using the Iterator() API we iterate over the map entry set.

        for (Map.Entry<String, String> entry : months.entrySet()) {
            System.out.println(entry.getKey() + “:” + entry.getValue());
        }

2- For loop

Next we iterate the map entry set using the classical for each method.

        Iterator<Map.Entry<String, String>> iterator = months.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            System.out.println(entry.getKey() + “:” + entry.getValue());
        }

3- Lambda expression

Lambda expressions were introduced in Java 8, this is the simplest way until now as we do not need to convert a map into a set of entries.

        months.forEach((k, v) -> System.out.println((k + “:” + v)));