Java 8 – Functional Interfaces

Functional Interfaces is one of the new important things of Java 8. In previous article, we had a little view about common use cases of Lambda Expression including Runnable and ActionListener. They are example of Functional Interfaces.

This tutorial helps you have deeper concept of Functional Interface, then some interfaces which are provided in java.util.function package such as Predicate and Function.

I. Functional Interfaces

An interface with only one abstract method inside is Functional Interface.

public interface MyFuncInterface {
	void doWork();
}

We add @FunctionalInterface annotation to annotate that an interface is Functional Interface. It can be used for making compiler errors when the interface is not a valid Functional Interface.
For example, when we have more than one abstract method inside, it throws a compiler error:

@FunctionalInterface
public interface MyFuncInterface {
	void doWork();
	void doAnotherWork();
}

Invalid '@FunctionalInterface' annotation; MyFuncInterface is not a functional interface
So, we can apply them simply:

@FunctionalInterface
public interface MyFuncInterface {
	void doWork();
}

public class MainApp {
	
	public static void executeFunction(MyFuncInterface func) {
		func.doWork();
	}

	public static void main(String[] args) {
		executeFunction(new MyFuncInterface() {
			
			@Override
			public void doWork() {
				System.out.println("invoke Function using Anonymous Inner Class");
			}
		});
		
		// with Lambda Expression
		executeFunction(() -> System.out.println("invoke Function using Lambda Expression"));
	}
}

For Functional Interface with only one method, we can make code lean and beautiful with Lambda Expression, it seem like that we pass a method as argument to a function. It is the convenience when using that kind of interface – take advantage of Java 8 Lambda Expression.

In previous article: Java 8 – Lambda Expressions, we have apply Lambda Expression for two Java Functional Interfaces:
Runnable with single abstract method run()
ActionListener with single abstract method actionPerformed(…)

		// Lambda Runnable
		Runnable r2 = () -> System.out.println("Hello world!");

		// Listener Lambda
		JButton testButton = new JButton("Test Button");
		testButton.addActionListener(e -> System.out.println("Lambda Listner Detected"));
II. java.util.function Package

Java 8 provides the java.util.function package with a number of standard functional interfaces which are designed as a starter set for developers, these are some of them:
Predicate<T>: Represents a predicate (boolean-valued function) of one argument, functional method: test(Object).
Consumer<T>: Represents an operation that accepts a single input argument and returns no result, functional method: accept(Object).
Function<T,R>: Represents a function that accepts one argument and produces a result, functional method: apply(Object).
Supplier<T>: Provides an instance of a T (such as a factory), functional method: get().

This tutorial introduces 2 functional interfaces: Predicate and Function.

1. Predicate

Predicate interface has method test(Object) to return a boolean value. The idea for this functional interface is that an object is tested to be true or false.

@FunctionalInterface
public interface Predicate {
    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);
}

We use Predicate<T> interface to check if a number in list is suitable for specific condition by method test(T t), and the function checkList receive Predicate<Integer> object as an input parameter:

    public static void checkList(List list, Predicate predicate) {
        for (Integer i : list) {
            if (predicate.test(i)) {
                System.out.print(i + " ");
            }
        }
    }

Lambda expression is used to assign method operation to Predicate object or just as an input parameter:

    List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
		
    System.out.println("Display all numbers > 5 in list");
    Predicate predicate = i -> i > 5;
    checkList(list, predicate);

    System.out.println("\nDisplay all numbers < 5 in list");
    checkList(list, i -> i < 5);

Run these statement, we will have the result:

Display all numbers > 5 in list:
6 7 8 9 
Display all numbers < 5 in list:
1 2 3 4 
2. Function

Function<T,R> interface takes a generic class T and returns a generic class R by the method apply(T t);

@FunctionalInterface
public interface Function {
    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);
}

To be clear, look at the example below.
This is Customer class:

public class Customer {
	private String firstName;
	private String lastName;

	public Customer(String firstName, String lastName) {
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	@Override
	public String toString() {
		return String.format("Customer[firstName='%s', lastName='%s']", firstName, lastName);
	}

	public String printName(Function f) {
		return f.apply(this);
	}
}

To make the print method more flexible than toString() with the modified printing function input, we have this method:

	public String printName(Function f) {
		return f.apply(this);
	}

A Function f will be passed to the method and a String will be returned corresponding to Customer. The method apply processes a lambda expression which determines what kind of Customer information is returned.

This is the testing code:

    System.out.println("\n=== Test Function ===");
    List customers = new ArrayList<>();
    customers.add(new Customer("Jack", "Smith"));
    customers.add(new Customer("Adam", "Johnson"));

    Function displayFullName = customer -> {
        return customer.getFirstName() + " " + customer.getLastName();
    };

    for (Customer customer : customers) {
        System.out.println(customer.printName(displayFullName));
    }

    System.out.println("=== Uppercase FirstName ===");
    for (Customer customer : customers) {
        System.out.println(customer.printName(c -> {
            return c.getFirstName().toUpperCase();
        }));
    }

And the result in Console Window:

=== Test Function ===
Jack Smith
Adam Johnson
=== Uppercase FirstName ===
JACK
ADAM
III. Source code

Technology:
- Java 8
- Eclipse Mars.1 Release (4.5.1)
funtionalinterface

57 thoughts on “Java 8 – Functional Interfaces”

  1. hey there and thank you for your information – I have definitely picked up anything new from right here.

    I did however expertise several technical issues using
    this web site, since I experienced to reload the site many times previous to I could get it to load properly.

    I had been wondering if your hosting is OK? Not that I am
    complaining, but slow loading instances times will sometimes affect your placement in google and could damage your high-quality score if
    ads and marketing with Adwords. Well I am adding this RSS to my email and could look out
    for a lot more of your respective fascinating content.

    Ensure that you update this again very soon.

  2. Heya! I just wanted to ask if you ever have any issues with hackers?
    My last blog (wordpress) was hacked and I ended up
    losing many months of hard work due to no back up.

    Do you have any methods to prevent hackers?

  3. I loved as much as you will receive carried out right here.
    The sketch is attractive, your authored subject matter stylish.
    nonetheless, you command get got an nervousness over that you wish be
    delivering the following. unwell unquestionably come more formerly again since exactly the same
    nearly a lot often inside case you shield this hike.

  4. I think everything composed made a bunch of sense.

    But, what about this? what if you wrote a catchier title?
    I am not suggesting your content is not solid., however what if you added something to maybe grab people’s attention? I mean ozenero | Mobile & Web Programming Tutorials is a
    little vanilla. You might look at Yahoo’s front page and see how they create post titles to get people to click.
    You might add a video or a pic or two to get readers excited about everything’ve written. In my opinion, it could bring your posts a little bit
    more interesting.

  5. Tһank you, I’ve jst beеn looking foг information about this subject for ages and yⲟurs is the
    gгeatest I have came upon till now. But, what about the
    botom line? Ꭺre you sure іn regards to tһe ѕupⲣly?

  6. Sweet blog! I found it while surfing around on Yahoo News.
    Do you have any suggestions on how to get listed in Yahoo News?
    I’ve been trying for a while but I never seem to get there!
    Appreciate it

  7. Simply desire to say your article is as astounding. The clearness in your submit is just spectacular and that i could
    assume you’re knowledgeable on this subject. Fine with your permission let me to
    snatch your feed to stay updated with coming near near post.
    Thank you one million and please continue the rewarding work.

  8. Please let me know if you’re looking for a author for your site.
    You have some really great articles and I believe I
    would be a good asset. If you ever want to take some of the load off, I’d absolutely love to write some articles for your blog in exchange for a link back to mine.
    Please send me an e-mail if interested. Cheers!

  9. Howdy! Do you know if they make any plugins to help with Search Engine Optimization? I’m trying
    to get my blog to rank for some targeted keywords but I’m not seeing very good results.
    If you know of any please share. Many thanks!

  10. Attractive component to content. I simply stumbled upon your website and in accession capital to assert that I get
    in fact enjoyed account your weblog posts. Anyway I will be subscribing on your augment and even I achievement you
    get entry to constantly fast.

  11. Greate post. Keep writing such kind of information on your blog.
    Im really impressed by it.
    Hi there, You have performed an excellent job.
    I will definitely digg it and individually recommend to my friends.
    I’m confident they’ll be benefited from this web site.

  12. I was recommended this web site by my cousin. I am not sure whether this post is written by him
    as nobody else know such detailed about my problem. You are wonderful!

    Thanks!

  13. My brother suggested I might like this website.
    He was entirely right. This post actually made my day. You cann’t imagine simply how much time I had spent for this info!
    Thanks!

  14. I think this is among the most important information for me.

    And i’m glad reading your article. But wanna remark
    on few general things, The web site style is great,
    the articles is really great : D. Good job, cheers

  15. Great blog! Is your theme custom made or did you download
    it from somewhere? A theme like yours with a few simple adjustements would really make my blog stand out.
    Please let me know where you got your theme. With thanks

  16. Have you ever thought about creating an ebook or guest authoring on other
    blogs? I have a blog based on the same ideas you discuss and would love to have
    you share some stories/information. I know my subscribers would value
    your work. If you are even remotely interested, feel free to shoot me an email.

  17. Good day! I know this is kinda off topic but I was wondering if you knew
    where I could locate a captcha plugin for my comment form?
    I’m using the same blog platform as yours
    and I’m having problems finding one? Thanks a lot!

  18. Great beat ! I would like to apprentice while you amend your site, how
    can i subscribe for a blog web site? The account helped me
    a acceptable deal. I had been tiny bit acquainted of this
    your broadcast provided bright clear concept

  19. whoah this blog is wonderful i like reading your articles.
    Stay up the good work! You understand, a lot of people are
    hunting round for this info, you could aid them greatly.

  20. My family members every time say that I am wasting my time here at net,
    except I know I am getting knowledge all the time by reading thes pleasant articles.

  21. I just like the valuable information you supply for your articles.
    I’ll bookmark your weblog and check again here frequently.
    I’m slightly sure I will learn many new stuff right here!
    Good luck for the next!

  22. Hi are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and create my own. Do you
    need any html coding expertise to make your own blog?

    Any help would be really appreciated!

  23. Somebody necessarily help to make severely posts I’d state.

    This is the very first time I frequented your website page
    and so far? I surprised with the analysis you made to create this actual
    submit extraordinary. Great process!

  24. Fantastic beat ! I would like to apprentice whilst you amend your web site, how can i subscribe for a blog website?
    The account helped me a acceptable deal. I were a little bit acquainted of this your broadcast provided vibrant transparent idea

  25. Do you have a spam issue on this blog; I also am a blogger, and I was
    wanting to know your situation; we have created some nice procedures and we
    are looking to trade strategies with other folks, why not shoot me an email if interested.

  26. First off I want to say terrific blog! I had a quick question which I’d like to ask if
    you do not mind. I was curious to find out how you center yourself and clear your head
    before writing. I have had trouble clearing my thoughts in getting my
    ideas out there. I truly do enjoy writing but it just seems like
    the first 10 to 15 minutes are lost simply just trying to figure out how to begin. Any suggestions or hints?

    Cheers!

  27. I was wondering if you ever considered changing the structure
    of your site? Its very well written; I love what youve got to say.
    But maybe you could a little more in the way of content
    so people could connect with it better. Youve got an awful lot of text for only having 1 or 2 pictures.
    Maybe you could space it out better?

  28. Great goods from you, man. I’ve understand your stuff previous
    to and you are just extremely fantastic. I really like what you have acquired
    here, really like what you are saying and the way in which you say it.
    You make it entertaining and you still take care
    of to keep it smart. I can not wait to read far more from
    you. This is really a terrific website.

  29. Hello there, just became aware of your blog through Google, and found that it’s really informative.
    I am going to watch out for brussels. I will be
    grateful if you continue this in future. A lot of people will be benefited from your writing.

    Cheers!

  30. Hello there, just became aware of your blog through Google, and found that it’s really informative.
    I am going to watch out for brussels. I will be
    grateful if you continue this in future. A lot of people will be benefited from your writing.

    Cheers!

  31. My brother recommended I might like this blog. He was entirely right.
    This post truly made my day. You cann’t imagine simply how much time I had spent for this
    information! Thanks!

  32. I loved as much as you will receive carried out right here.
    The sketch is attractive, your authored material stylish. nonetheless,
    you command get got an impatience over that you wish be delivering the following.
    unwell unquestionably come more formerly again as exactly the same nearly very often inside case you
    shield this increase.

  33. This design is incredible! You definitely know how to keep a reader amused.
    Between your wit and your videos, I was almost moved
    to start my own blog (well, almost…HaHa!) Fantastic job.
    I really enjoyed what you had to say, and more than that, how you presented it.

    Too cool!

  34. Link exchange is nothing else however it
    is just placing the other person’s web site link on your page at suitable place and
    other person will also do similar in support of
    you.

  35. Exceptional post however I was wondering if you could write
    a litte more on this topic? I’d be very thankful if
    you could elaborate a little bit further. Thank you!

  36. We’re a group of volunteers and starting
    a new scheme in our community. Your website provided us with valuable information to
    work on. You’ve done a formidable job and our entire
    community will be grateful to you.

  37. Oh my goodness! Amazing article dude! Thanks,
    However I am going through issues with your RSS. I don’t
    know why I cannot subscribe to it. Is there anybody else
    having identical RSS problems? Anyone who knows the solution can you kindly respond?
    Thanx!!

Leave a Reply

Your email address will not be published. Required fields are marked *