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));
}
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!