Quick Index
Steps



Problem Statement


Use the same problem statement used for the algorithm problem

Convert the psuedocode solution to Java.





































































































Hints







































































































Solution


public class FunctionPassingDrill {

	/**Selects a subset of passed collection per selectFct*/
	public static <T> List<T> selectElements(List<T> elements, Function<T, Boolean> selectFct) {
		List<T> newElements = new ArrayList<>();
		for (T nextElem: elements) {
			if (selectFct.apply(nextElem))
				newElements.add(nextElem);
		}
		return newElements;
	}

	/**Returns new collection by rejecting elements in passed collection per rejectFct*/
	public static <T> List<T> rejectElements(List<T> elements, Function<T, Boolean> rejectFct) {
		Function<T, Boolean> invertedFct;
		invertedFct = (x) -> !rejectFct.apply(x);
		return FunctionPassingDrill.selectElements(elements, invertedFct);
	}

}

//_test_

private void experiment() {
	println("\ntest_rejectElements");
	List<Integer> nums = Arrays.asList(10, 11, 12, 13, 14, 15), newNums;
	println("Data: " + nums);
	//input integer, output boolean
	Function<Integer, Boolean> isOddFct, smallNumberFct;

	//fct returns true if x is odd
	isOddFct = (x) -> x % 2 == 1;
	newNums = FunctionPassingDrill.rejectElements(nums, isOddFct);
	println("Rejecting odd: " + newNums);

	//fct returns true if x is equal or less than 12
	smallNumberFct = (x) -> x <= 12;
	newNums = FunctionPassingDrill.rejectElements(nums, smallNumberFct);
	println("Rejecting Smaller Numbers (less than or equal to 12): " + newNums);

	List<String>
		names = Arrays.asList("Asha", "Acheampong", "Mo"),
		newNames;
	println("Names: " + names);
	//input string, output boolean
	Function<String, Boolean> isShortStringFct;
	isShortStringFct = (str) -> str.length() < 5;
	newNames = FunctionPassingDrill.rejectElements(names, isShortStringFct);
	println("Rejecting Shorter Strings: " + newNames);

}