How to convert For loop using Stream in Java

Creating a Map of Applicant object, where I filter out on the applicant’s age. I only need the first name and last name of the applicant. Using the application ID as the key. The ID is generated integer and unique. Also, testing for null, don’t want that in there. I am using a traditional for loop where I am most comfortable at. But I want to use the Java 8 Stream instead. How is it done?

My code for this is below:

        Applicant a1 = new Applicant();
        a1.setId(1001);
        a1.setFirstName("Joseph");
        a1.setLastName("Dey");
        a1.setAge(25);

        Applicant a2 = new Applicant();
        a2.setId(2001);
        a2.setFirstName("Maxine");
        a2.setLastName("Summers");
        a2.setAge(21);

        Applicant a3 = new Applicant();
        a3.setId(3001);
        a3.setFirstName("Jimmy");
        a3.setLastName("Cox");
        a3.setAge(17);

        Applicant a4 = null;

        List<Applicant> list = new ArrayList<>();
        list.add(a1);
        list.add(a2);
        list.add(a3);
        list.add(a4);

        Map<Integer, String> map = new HashMap<>();
        for (Applicant a : list) {
            if (a != null && a.getAge() > 18) {
                map.put(a.getId(), a.getFirstName() + " " + a.getLastName());
            }
        }

ANSWER

By Statement Lambda in Collectors.toMap – right-hand side is a block. This can become longer to write but sometimes when you have to do more transformations, then it can’t be avoided.

1       Map<Integer, String> map = list.stream()
2                .filter(applicant -> applicant != null)
3                .filter(applicant -> applicant.getAge() >= 18)
4                .collect(Collectors.toMap(applicant -> applicant.getId(), applicant -> {
5                    return applicant.getFirstName() + " " + applicant.getLastName();
6                }));

By Expression Lambda in Collectors.toMap – right-hand side is an expression.

1       Map<Integer, String> map = list.stream()
2                .filter(applicant -> applicant != null)
3                .filter(applicant -> applicant.getAge() >= 18)
4                .collect(Collectors.toMap(applicant -> applicant.getId(), applicant -> applicant.getFirstName() + " " + applicant.getLastName()));

In both cases above, line #2 the Lambda can be replaced with method reference too. It will look like:

.filter(Objects::nonNull)

And on line #4, the same can be done for the Lamba replacing it with a method reference. It will look like:

.collect(Collectors.toMap(Applicant::getId,  // rest of code ommitted