LearnFrenzy
Sign in Take a free test

Lambda Expressions · Exercise 4 of 4

Lambda Expressions Lambda Expressions Programs

  • 10 questions
  • Page 1 of 1
  • Answers explained
0Attempted
0Correct
0Wrong
Directions

Java programs that use lambdas, functional interfaces and method references to write concise, flexible code. Write each one yourself first, then open the solution – every solution was compiled and run on Java 21, and the output shown is the real output.

Question 1 Easy

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.

Question page & discussion
Question 2 Medium

Store named discount rules as Function<Double, Double> lambdas in a LinkedHashMap, apply each to a cart total, and also chain the "coupon" and "member" rules with andThen.

Question page & discussion
Question 3 Medium

Write a generic retry(Supplier<T> action, int attempts, Predicate<Exception> retryOn) that retries only for matching exceptions; test with a flaky operation and with a non-retryable failure.

Question page & discussion
Question 4 Easy

Write a Button class that keeps a list of Consumer<String> listeners and notifies them on click; register lambdas and a method reference, then click twice.

Question page & discussion
Question 5 Medium

Build password rules as a Map of message → Predicate<String>, check several passwords and print which rules each fails; combine all rules into one predicate with reduce-style and().

Question page & discussion
Question 6 Medium

Build a text-cleaning pipeline from a list of UnaryOperator<String> steps (trim, collapse spaces, mask digits, capitalise) combined into one Function with andThen, and apply it to several inputs.

Question page & discussion
Question 7 Easy

Sort a list of Employee records by department, then by salary descending, then by name; also print the highest-paid employee in each department using a loop and a BinaryOperator.

Question page & discussion
Question 8 Hard

Write memoize(Function<T, R>) that returns a caching function, count how often the real function runs, and use it to speed up a slow "price lookup" and a recursive Fibonacci.

Question page & discussion
Question 9 Medium

Model a traffic light whose transitions are stored as a Map from state to UnaryOperator, with timing per state; simulate the light for 100 seconds and print each change.

Question page & discussion
Question 10 Medium

Create a list of Callable<Integer> lambdas (one of them throws), run each one, sum the successful results and report failures – Callable lambdas may throw checked exceptions.

Question page & discussion
All exercises doneBack to Lambda ExpressionsRevise the concepts or pick another topic

Ready to test your Programming?

Timed online tests with instant scores and explanations.

Search LearnFrenzy

Esc

Quick links