Quick Index
Steps



Demo


Here is a demo (1 min 17 seconds)

Problem Statement


Use the same problem statement used for the algorithm problem

Convert the psuedocode solution to Java.





































































































Hints







































































































Solution


public class FunctionPassingDrill {

	/**Returns new collection using mapFct to produce new elements */
	public static <T, S> List<S> mapElements(List<T> elements, Function<T, S> mapFct) {
		List<S> newElements = new ArrayList<>();
		for (T nextElem: elements) {
			S newElem = mapFct.apply(nextElem);
			newElements.add(newElem);
		}
		return newElements;
	}

}

//_test_
private void experiment() {
	println("\ntest_mapElements");
	List<Integer> nums = Arrays.asList(2, 3, 4), newNums;
	//input integer, output integer
	Function<Integer, Integer> squareFct;
	println("Data: " + nums);
	//Squares
	squareFct = (x) -> x * x;
	newNums = FunctionPassingDrill.mapElements(nums, squareFct);
	println("Squares: " + newNums);

	List<String> names = Arrays.asList("Asha", "Acheampong", "Mo");
	List<Integer> lengths;
	println("Data: " + names);
	//input string, output integer
	Function<String, Integer> lengthFct;
	lengthFct = (name) -> name.length();
	lengths = FunctionPassingDrill.mapElements(names, lengthFct);
	println("Lengths: " + lengths);
}