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.
- Create a
BiPredicate
to check ifage
is greater than 18 andstatus
is "Active". - Inside
forEach()
, use theif
statement to evaluate the user based on theBiPredicate
. - If the user satisfies the condition, print the user to the console.
Ratkaisu
solution
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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ää?
Kiitos palautteestasi!
Osio 1. Luku 14
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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ä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme