Java代写:COMPS311 Lambdas and Streams

代写Java作业,练习Java中的高级用法,如Lambda, stream等。

Java

Question 1 - Lambdas and streams

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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: " + distinctMethodNamesInOrder(cls));
System.out.println("Method with most parameters: " + methodWithMostParameters(cls).get());
System.out.println("Method names to counts: " + methodNamesToCounts(cls));
}
}

This is a sample output of executing the completed program on the String class

> java a1.MethodsEx class java.lang.String
Number of methods: 101
Method names: [value, equals, length, toString, hashCode, getChars, compareTo, compareTo, indexOf, indexOf, indexOf, indexOf, indexOf, checkIndex, valueOf, valueOf, valueOf, valueOf, valueOf, valueOf, valueOf, valueOf, valueOf, coder, rangeCheck, codePoints, isEmpty, charAt, codePointAt, codePointBefore, codePointCount, offsetByCodePoints, getBytes, getBytes, getBytes, getBytes, getBytes, contentEquals, contentEquals, nonSyncContentEquals, equalsIgnoreCase, compareToIgnoreCase, regionMatches, regionMatches, startsWith, startsWith, endsWith, lastIndexOf, lastIndexOf, lastIndexOf, lastIndexOf, lastIndexOf, substring, substring, subSequence, concat, replace, replace, matches, contains, replaceFirst, replaceAll, split, split, join, join, toLowerCase, toLowerCase, toUpperCase, toUpperCase, trim, strip, stripLeading, stripTrailing, isBlank, lines, lines, indent, indent, indexOfNonWhitespace, lastIndexOfNonWhitespace, transform, chars, toCharArray, format, format, copyValueOf, copyValueOf, intern, repeat, isLatin1, checkOffset, checkBoundsOffCount, checkBoundsBeginEnd, valueOfCodePoint, describeConstable, resolveConstantDesc, resolveConstantDesc, lambda$indent$2, lambda$indent$1, lambda$indent$0]
Distinct method names: [charAt, chars, checkBoundsBeginEnd, checkBoundsOffCount, checkIndex, checkOffset, codePointAt, codePointBefore, codePointCount, codePoints, coder, compareTo, compareToIgnoreCase, concat, contains, contentEquals, copyValueOf, describeConstable, endsWith, equals, equalsIgnoreCase, format, getBytes, getChars, hashCode, indent, indexOf, indexOfNonWhitespace, intern, isBlank, isEmpty, isLatin1, join, lambda$indent$0, lambda$indent$1, lambda$indent$2, lastIndexOf, lastIndexOfNonWhitespace, length, lines, matches, nonSyncContentEquals, offsetByCodePoints, rangeCheck, regionMatches, repeat, replace, replaceAll, replaceFirst, resolveConstantDesc, split, startsWith, strip, stripLeading, stripTrailing, subSequence, substring, toCharArray, toLowerCase, toString, toUpperCase, transform, trim, value, valueOf, valueOfCodePoint]
Method with most parameters: static int java.lang.String.indexOf(byte[],byte,int,java.lang.String,int)
Method names to counts: {toCharArray=1, coder=1, codePointAt=1, replace=2, checkOffset=1, resolveConstantDesc=2, checkBoundsOffCount=1, compareTo=2, describeConstable=1, getBytes=5, strip=1, split=2, trim=1, toUpperCase=2, join=2, equalsIgnoreCase=1, codePointBefore=1, indexOf=5, compareToIgnoreCase=1, codePoints=1, checkBoundsBeginEnd=1, lastIndexOfNonWhitespace=1, toLowerCase=2, lambda$indent$2=1, format=2, lambda$indent$1=1, lambda$indent$0=1, concat=1, matches=1, contains=1, endsWith=1, nonSyncContentEquals=1,

Question 2 - Interface

The WindowListener interface, containing 7 abstract methods, is used to handle events of operating a Swing window, or frame.

  • (a) Create a subinterface of WindowListener, called WindowClosingListener, that implements all except the windowClosing method of WindowListener. Specifically, implement each of the 6 methods as a default method with an empty method body.
  • (b) Create a program, called WindowClosingEx, that displays a Swing frame, and uses the WindowClosingListener interface to exit the program when the frame is closed.

Skeleton code of the interface and the class is provided to you as follows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// package and import statements

interface WindowClosingListener ... {
...
}

public class WindowClosingEx {
public static void main(String[] args) {
var frame = new JFrame("Window Closer Demo");
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
...
frame.setVisible(true);
}
}

Question 3 - Concurrency

In this question, you develop two versions of a program that concurrently counts the words in the Java programs within a directory. The program displays the total number of words in the files, and the execution time. Words are delimited by whitespaces, as the tokens of a Scanner object by default. A Java program is a file with the .java extension, and may be located in some nested subdirectory of the specified directory.

  • (a) Develop a program, called WordCountByThreadPool, that counts the words using a thread pool. Each Java program is processed in a thread from the thread pool. The program should have two command-line parameters - the directory that contains Java programs, and the maximum number of threads in the thread pool
  • (b) Develop a program, called WordCountByParallelStream, that counts the words using a parallel stream. There should have one command-line parameter - the directory that contains Java programs.

You are not required to implement input validation of command-line parameters or handling of I/O errors.

These are sample outputs of executing the programs.

> java a1.WordCountByThreadPool jdksrc 1
Total number of words: 22587514
Execution time: 12221 ms
> java a1.WordCountByThreadPool jdksrc 4
Total number of words: 22587514
Execution time: 3813 ms
> java a1.WordCountByParallelStream jdksrc
Total number of words: 22587514
Execution time: 6368 ms

Question 4 - Networking

In this question, you develop a pair of client and server programs that communicate by transferring binary objects using object streams. In other words, they use the writeObject method of ObjectOutputStream, and the readObject method of ObjectInputStream.

  • (a) Develop the multithreaded server program, called IntegersServer, that services clients concurrently and repeatedly. You may use a thread pool or create individual threads to implement multithreading in the program. For each connected client, the server receives an array of primitive integers (int[]), computes the sum and mean of the integers, and sends the sum and mean to the client in an array of 2 primitive double values (double[]). In case of any error, the server sends a String object of “error” to the client. The server program should have one optional command-line parameter - the port to listen, default 2000.
  • (b) Develop the client program, called IntegersClient, that works with the server. The client first prompts the user for the integers, puts them in an array of primitive integers (int[]), sends the array to the server, and receives an object from the server. If the object returned from the server is an array of double values (double[]), retrieve and display the sum and mean values from it. Otherwise, display the object as a string. The client program should have two optional command-line parameters - the server hostname or address, default “localhost”, and the server port, default 2000.

Hint: When an ObjectInputStream object is created, it reads some header data which is written by an ObjectOutputStream object. If each of the client and server creates an ObjectInputStream before an ObjectOutputStream, both of them would wait for header data and cannot proceed, which leads to a deadlock. Therefore, make sure to have one or both of the client and server creating an ObjectOutputstream before an ObjectInputStream. Refer to the API documentation of the ObjectInputStream class.

These are sample outputs of running the server and client programs.

> java a1.IntegersServer 2000
Server listening: ServerSocket[addr=0.0.0.0/0.0.0.0,localport=2000]
Client: Socket[addr=/127.0.0.1,port=54524,localport=2000]
> java a1.IntegersClient localhost 2000
Enter integers (separated by spaces): 1 2 3 4
Sum = 10.0
Mean = 2.5

Submit

  • Submit a report containing answer to the required questions. Your report should be stored in a Word format.
  • You should then ZIP up the report document with other required files (such as Java program files).