Accounts

Report a typo

Given a class Account(number: String, balance: Long, locked: boolean), the list accounts of type List<Account> and the method filter(List<T> elems, Predicate<T> predicate) for filtering the given list of type T by the predicate.

The class Account has the following get methods: getNumber(), getBalance(), isLocked() for retrieving the values of the corresponding fields.

Write code for filtering the accounts list using the filter method in two ways:

  1. get all non-empty accounts (balance > 0) and save it to the variable nonEmptyAccounts
  2. get all non-locked accounts with too much money (balance >= 100 000 000) and save it to the variable accountsWithTooMuchMoney

Important. Use the given code template for your solution. Do not change it!

Example of using the filter method. The code below gets only even numbers from the list.

List<Integer> numbers = ...
List<Integer> evenNumbers = filter(numbers, number -> number % 2 == 0);

PS: it's often called behavior parametrization because the behavior of the method filter is dependent on the given predicate.

Write a program in Java 17
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.function.Predicate;
import java.util.stream.Collectors;

class Main {

public static void printFilteredAccounts(List<Account> accounts) {
List<Account> nonEmptyAccounts = // write your code here
List<Account> accountsWithTooMuchMoney = // write your code here

// Don't change the code below
nonEmptyAccounts.forEach(a -> System.out.print(a.getNumber() + " "));
accountsWithTooMuchMoney.forEach(a -> System.out.print(a.getNumber() + " "));
}

public static <T> List<T> filter(List<T> elems, Predicate<T> predicate) {
return elems.stream()
.filter(predicate)
.collect(Collectors.toList());
}

public static void main(String[] args) {

final Scanner scanner = new Scanner(System.in);
final int n = Integer.parseInt(scanner.nextLine());
final List<Account> accounts = new ArrayList<>();

for (int i = 0; i < n; i++) {
final String[] values = scanner.nextLine().split("\\s+");
final Account acc = new Account(
values[0], Long.parseLong(values[1]), Boolean.parseBoolean(values[2])
);
accounts.add(acc);
}
___

Create a free account to access the full topic