Skip to content

Instantly share code, notes, and snippets.

@sye8
Last active February 2, 2018 00:54
Show Gist options
  • Save sye8/b2321c878512b74104ef815bbd99f4af to your computer and use it in GitHub Desktop.
Save sye8/b2321c878512b74104ef815bbd99f4af to your computer and use it in GitHub Desktop.
CSC 172 Lab Java Functional Interface

Note on Java Functional Interface

If you read this, and still don't understand what is the syntax, read on:

A Java Function is like a method, but is more powerful than a method. For the purpose of this lab, you would only need to know that a fucntion, is like a method.

At the meantime, a Function is an Object (instance of a class), and so to start coding up your Function, you need to declare a Function, just like any other Object.

When you declare an Object, you do this:

Type name = //blah

And so, when you declare your function, it looks like this:

Function<paramType, returnType> name

Here, the type is a Function that takes in parameter of type paramType and returns an Object of type returnType

And so, if your Function takes in a Character array and spits out a Character, your type looks like this:

Function<Character[], Character> findMax

And after declaring the Function, you would need to define it. To define a Function, you would need to specify the input parameter and how the Function is going to return a value.

Function<paramType, returnType> name = param -> { //do stuff };

And so your function would look like this:

Function<Character[], Character> findMax = charArr -> { 
    //Do stuff 
    return maxChar; 
};

Note that, your "do stuff" part may take several lines, and must include a return statement, just like your other methods.

However, since Function is an Object, you cannot call the Function as you call a method. Instead, you call the instance method .apply(param) to apply the Function on the given parameter. It will look like this:

findMax.apply(charArr);

Hope you find this useful and good luck!

Sifan Ye

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment