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

book
Challenge: Filtering Users by Two Criteria

Tehtävä

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.

Ratkaisu

java

solution

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;
Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 1. Luku 14
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;

Kysy tekoälyä

expand
ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

some-alt