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.
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));
}
}
[Hyderabad, Bengaluru, Thiruvananthapuram] [9, 9, 18] [AGRA, DELHI]
Passing behaviour (the Predicate and Function) makes one method useful for countless filters and transformations.