2

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.");
    }
}
John Kugelman
  • 307,513
  • 65
  • 473
  • 519
Strom
  • 89
  • 1
  • 8
  • The [documentation](https://docs.oracle.com/javase/9/docs/api/java/util/stream/Stream.html#toArray-java.util.function.IntFunction-) says "Returns an array containing the elements of this stream, using the provided generator function to allocate the returned array," – markspace May 29 '18 at 01:38
  • If you want to see how lambda's translate in 'regular code' and the other way around, you can try IntelliJ. This editor recognizes parts of code that can be rewritten to lambda's and can translate lambda's back to pre-java8. – Sven May 29 '18 at 04:37

2 Answers2

3

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];
    }
});
John Kugelman
  • 307,513
  • 65
  • 473
  • 519
0

toArray takes an implementation of the IntFunction interface. Without a lambda it would look like this:

private static class MyArrayGenerator implements IntFunction<String[]> {
    @Override
    public String[] apply(int size) {
        return new String[size];
    }
}

[...]

    stringArray = streamData.toArray(new MyArrayGenerator());

Because IntFunction is a FunctionalInterface with a single abstract method, you can define one using the compact lambda syntax. The types will be inferred by the compiler.

jspcal
  • 47,335
  • 4
  • 66
  • 68