LearnFrenzy
Sign in Take a free test

Lambda Expressions · Lambda Expressions Programs · Question 1

Write your own filter and map with lambdas in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Write generic filter(List<T>, Predicate<T>) and map(List<T>, Function<T, R>) methods (without streams) and use them to find long city names and their lengths.

Solution
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;

public class Main {
    static <T> List<T> filter(List<T> items, Predicate<? super T> keep) {
        List<T> out = new ArrayList<>();
        for (T t : items) if (keep.test(t)) out.add(t);
        return out;
    }

    static <T, R> List<R> map(List<T> items, Function<? super T, ? extends R> f) {
        List<R> out = new ArrayList<>();
        for (T t : items) out.add(f.apply(t));
        return out;
    }

    public static void main(String[] args) {
        List<String> cities = List.of("Pune", "Hyderabad", "Agra", "Bengaluru", "Delhi", "Thiruvananthapuram");
        List<String> longOnes = filter(cities, c -> c.length() > 5);
        System.out.println(longOnes);
        System.out.println(map(longOnes, String::length));
        System.out.println(map(filter(cities, c -> c.startsWith("A") || c.startsWith("D")), String::toUpperCase));
    }
}

Output Verified by compiling and running

[Hyderabad, Bengaluru, Thiruvananthapuram]
[9, 9, 18]
[AGRA, DELHI]

Passing behaviour (the Predicate and Function) makes one method useful for countless filters and transformations.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links