The following program, with some methods to be completed, explores methods declared in a class. Complete the four methods by returning an expression that uses the stream API, lambda expressions and method references as appropriate.

computer science

Description

Question 1 – Lambdas and streams [20 marks]

 

The following program, with some methods to be completed, explores methods declared in a class. Complete the four methods by returning an expression that uses the stream API, lambda expressions and method references as appropriate.

(a) The method methodNames returns the names of all methods of a class in a list of strings.

(b) The method distinctMethodNamesInOrder returns the names of all methods of a class, with distinct names and in alphabetical order, in a list of strings.

(c) The method methodWithMostParameters returns the method with the maximum number of parameters in an Optional of Method object. If there are two or more methods with the same maximum number of parameters, return any one of them. If the class has no method, return an empty Optional object.

(d) The method methodNamesToCounts returns a map of which the key is the method name and the value is the number of (overloaded) methods with that name.

The method numOfMethods method, provided as an example, returns the number of methods declared in a class. The main method can be used to test the methods

package a1;

 

import java.lang.reflect.Method;

import java.util.*;

import java.util.stream.*;

 

public class MethodsEx {

static long numOfMethods(Class<?> cls) {

return Stream.of(cls.getDeclaredMethods()).count();

}

 

static List<String> methodNames(Class<?> cls) {

// (a)

}

 

static List<String> distinctMethodNamesInOrder(Class<?> cls) {

// (b)

}

 

static Optional<Method> methodWithMostParameters(Class<?> cls) {

// (c)

}

 

static Map<String, Long> methodNamesToCounts(Class<?> cls) {

// (d)

}

 

public static void main(String[] args)

throws ClassNotFoundException {

var cls = args.length > 0 ? Class.forName(args[0])

: String.class;

System.out.println(cls);

System.out.println("Number of methods: " + numOfMethods(cls)); System.out.println("Method names: " + methodNames(cls)); System.out.println("Distinct method names: "

 

3



Related Questions in computer science category