Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Challenge: Filtering Users by Two Criteria | Fundamentals and Functional Capabilities of Stream API
Stream API

book
Challenge: Filtering Users by Two Criteria

Uppgift

Swipe to start coding

Filter the users who are over 18 years old and have an "Active" status, then print them to the screen.

  1. Create a BiPredicate to check if age is greater than 18 and status is "Active".
  2. Inside forEach(), use the if statement to evaluate the user based on the BiPredicate.
  3. If the user satisfies the condition, print the user to the console.

Lösning

solution.java

solution.java

package com.example;

import java.util.List;
import java.util.Arrays;
import java.util.function.BiPredicate;

public class Main {
public static void main(String[] args) {
// Creating a list of users
List<User> users = Arrays.asList(
new User("Alice", 22, "Active"),
new User("Bob", 17, "Inactive"),
new User("Charlie", 25, "Active"),
new User("David", 16, "Active")
);

// Defining `BiPredicate` to check `age` and `status`
BiPredicate<Integer, String> isEligible = (age, status) -> age > 18 && status.equals("Active");

// Using `forEach` to iterate over the list
users.forEach(user -> {
// If the user satisfies the conditions, print the user
if (isEligible.test(user.getAge(), user.getStatus())) {
System.out.println(user); // Print the user
}
});
}
}

class User {
private String name;
private int age;
private String status;

public User(String name, int age, String status) {
this.name = name;
Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 14
single

single

package com.example;

import java.util.List;
import java.util.Arrays;
import java.util.function.BiPredicate;

public class Main {
public static void main(String[] args) {
// Creating a list of users
List<User> users = Arrays.asList(
new User("Alice", 22, "Active"),
new User("Bob", 17, "Inactive"),
new User("Charlie", 25, "Active"),
new User("David", 16, "Active")
);

// Defining `BiPredicate` to check `age` and `status`
BiPredicate<Integer, String> isEligible = (age, status) -> ___ && status.___;

// Using `forEach` to iterate over the list
users.forEach(user -> {
// If the user satisfies the conditions, print the user
if (___.test(___, ___)) {
___
}
});
}
}

class User {
private String name;
private int age;
private String status;

public User(String name, int age, String status) {
this.name = name;

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

some-alt