I am having considerable difficulty understanding this toArray function. Can somebody please provide the full context of this method without using the lambda arrow or a double ::
colon method reference?
It is more helpful that I know the full non-shortened version of how this toArray
code should look and understand what the program is trying to do rather than memorizing certain expressions. It's more about programming literacy than anything.
The full context here is that I am trying to convert a stream reader from another class with preset data. The reader's data is converted to the Stream<String>
method and I aim to convert that streamData
into a String
array.
public List<WordCountResult> countWordOccurrences(BufferedReader reader) throws Exception {
try {
// word, occurrences
Map<String, Integer> data = new TreeMap<>(); //TreeMap arranges items by natural order.
Stream<String> streamData = reader.lines();
String[] stringArray;
stringArray = streamData.toArray(size -> new String[size]);
}
catch(Exception ex1) {
System.out.println("Processing error.");
}
}
toArray()
takes an IntFunction<String[]>
-- this is a function which receives an int
size and returns an array of that size. The non-lambda version looks like:
stringArray = streamData.toArray(new IntFunction<String[]>() {
@Override String[] apply(int size) {
return new String[size];
}
});