How to filter and return objects in Java stream?

In Java, you can use Stream to filter and return objects. Here is an example:

Assuming we have a list containing Person objects, we want to filter out people over the age of 18 based on a certain condition. We can use the filter() method to filter the list, and then use the collect() method to collect the filtered results into a new list.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Example {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("Alice", 20));
        personList.add(new Person("Bob", 25));
        personList.add(new Person("Charlie", 17));

        List<Person> filteredList = personList.stream()
                .filter(person -> person.getAge() > 18)
                .collect(Collectors.toList());

        for (Person person : filteredList) {
            System.out.println(person.getName() + " - " + person.getAge());
        }
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

In the example above, a list containing Person objects is first created. The list is then converted into a stream using the stream() method. Next, a Lambda expression is passed into the filter() method to filter out individuals over 18 years old. Finally, the collect() method is used to gather the filtered results into a new list.

Finally, use a for loop to iterate through the new list and output the name and age of each person. Running the above code will yield the following output:

Alice - 20
Bob - 25
bannerAds