Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Lekciq;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Scanner;
- import java.util.function.BiPredicate;
- import java.util.function.Function;
- public class FilterByAge {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- // Read number of entries
- int n = Integer.parseInt(scanner.nextLine());
- // Read name and age pairs
- List<Person> people = new ArrayList<>();
- for (int i = 0; i < n; i++) {
- String[] input = scanner.nextLine().split(", ");
- String name = input[0];
- int age = Integer.parseInt(input[1]);
- people.add(new Person(name, age));
- }
- // Read condition, age, and format
- String condition = scanner.nextLine();
- int ageLimit = Integer.parseInt(scanner.nextLine());
- String format = scanner.nextLine();
- // Define predicates and functions
- BiPredicate<Integer, Integer> ageCondition = getAgeCondition(condition);
- Function<Person, String> formatFunction = getFormatFunction(format);
- // Filter and print results
- people.stream()
- .filter(person -> ageCondition.test(person.age, ageLimit))
- .map(formatFunction)
- .forEach(System.out::println);
- }
- // Method to get age condition predicate
- private static BiPredicate<Integer, Integer> getAgeCondition(String condition) {
- if (condition.equals("younger")) {
- return (age, limit) -> age <= limit;
- } else if (condition.equals("older")) {
- return (age, limit) -> age >= limit;
- } else {
- throw new IllegalArgumentException("Invalid condition: " + condition);
- }
- }
- // Method to get format function
- private static Function<Person, String> getFormatFunction(String format) {
- switch (format) {
- case "name":
- return person -> person.name;
- case "age":
- return person -> String.valueOf(person.age);
- case "name age":
- return person -> person.name + " - " + person.age;
- default:
- throw new IllegalArgumentException("Invalid format: " + format);
- }
- }
- // Person class to store name and age
- private static class Person {
- String name;
- int age;
- Person(String name, int age) {
- this.name = name;
- this.age = age;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement