package rd222dv_assign1; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; public class FunctionPointers { public static void main(String[] args) { System.out.println("Part 1: Apply predicates"); List list = Arrays.asList(45, 3, 24, 16, 1, 1, 3, 8, 7, 6, 10, 12, 17, 22, 30); System.out.print("Print all numbers: "); Predicate all = n -> true; selectAndPrint(list, all); // System.out.print("\nPrint all odd numbers: "); Predicate odd = n -> n % 2 != 0; // Must be updated selectAndPrint(list, odd); System.out.print("\nPrint all numbers greater than 10: "); Predicate aboveTen = n -> n > 10; // Must be updated selectAndPrint(list, aboveTen); System.out.println("\n\nPart 2: Apply functions"); List numbers = Arrays.asList(1.0, 16.0, 25.0, 81.0); System.out.println("Original: " + numbers); System.out.println("Square root: " + applyFunction(numbers, Math::sqrt)); System.out.println("Power of two: " + applyFunction(numbers, FunctionPointers::powerOfTwo)); } // Prints all elements in the list where predicate evaluates to true public static void selectAndPrint(List list, Predicate predicate) { for(Integer n: list) { if(predicate.test(n)) { System.out.print(n + " "); } } } // Returns a new list containing the numbers resulting from applying fx // on the input list numbers private static List applyFunction(List numbers, Function fx) { List appliedNumbers = new ArrayList<>(); for (Double n : numbers) { appliedNumbers.add(Double.valueOf(fx.apply(n))); } return appliedNumbers; } private static Double powerOfTwo(Double d) { return d*d; // Must be updated } }