Avatar ·

How to filter a collection in Java by condition (predicate)?

Hello everyone! I'm new to Java and ran into this problem: I have a list of `Person` objects with `name` and `age` fields. I need to get only those who are over 18 years old. I know I can iterate with a `for` loop and add matching elements to a new list, but it looks cumbersome. I've heard that Java 8 introduced streams and lambdas, but I haven't figured out how to use them for filtering collections yet. Here's an example of my code: ```java List people = new ArrayList<>(); people.add(new Person("Alice", 22)); people.add(new Person("Bob", 17)); people.add(new Person("Charlie", 19)); // How to get a list of adults? // Currently doing it like this: List adults = new ArrayList<>(); for (Person p : people) { if (p.getAge() >= 18) { adults.add(p); } } ```