Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA PROBLEM This exercise is focused on making you more familiar with the usage

ID: 3750329 • Letter: J

Question

JAVA PROBLEM

This exercise is focused on making you more familiar with the usage of the lambda
expressions in conjunction with Functional Interfaces (namely IntPredicate)

We already know that the following piece of code allows us to evaluate IntPredicate for a
particular input value.

private static boolean applyPredicate(int value, IntPredicate predicate) {
return predicate.test(value);
}
It tells us whether our integer value satisfies the condition conveyed by the
predicate. e.g.

applyPredicate(2, x -> x > 100) returns false because 2 is not greater than 100
applyPredicate(15, x -> (x % 5 == 0)) returns true because 15 is divisible by 5


create a class TeenCount that implements the method public static int[] teenLess(int[] array)
which takes in an array of integers as the input, applies the appropriate predicate over all the elements of
the array and then returns a new array containing only those values which are not teens i.e. values which
don't lie between 13 and 19 inclusive. Feel free to use the applyPredicate() method in your program

Explanation / Answer

import java.util.function.IntPredicate;

import java.util.Scanner;

import java.util.ArrayList;

import java.util.List;

class TeenCount {

public static int[] teenLess(int[] array) {

List<Integer> temp_array = new ArrayList<Integer>();

for(int elem : array) {

boolean y = applypredicate(elem, temp -> (elem >= 13 && elem <= 19));

if(!y)

temp_array.add(elem);

}

return temp_array.stream().mapToInt(i->i).toArray();

}

public static boolean applypredicate(int value,IntPredicate predicate) {

return predicate.test(value);

}

}

class Driver {

public static void main(String args[] ) {

Scanner sc = new Scanner(System.in);

System.out.print(" Enter the range of the array : ");

int range = sc.nextInt();

int arr[] = new int[range];

System.out.println(" Enter "+ range + " elements : ");

for(int i=0;i<range;i++)

arr[i] = sc.nextInt();

int new_array[] = TeenCount.teenLess(arr);

if(new_array.length == 0 ) {

System.out.println(" No element exists to display ");

}

else {

System.out.println(" New Array is ");

for(int elem : new_array) {

System.out.print(elem + " ");

}

}

}

}