Lambdas: New to Java 8, New to Flukeshot

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 8955 Views - Last Post: 07 June 2014 - 10:12 PM

#16 SuperProgrammer  Icon User is offline

  • D.I.C Head

Reputation: 12
  • View blog
  • Posts: 58
  • Joined: 17-April 14

Re: Lambdas: New to Java 8, New to Flukeshot

Posted 07 June 2014 - 10:12 PM

I have used lambdas enough to be able to understand it. It is an easy to shorten your code because instead of writing the hole method of the functional interface/listener, you could do:

exampleButton.addActionListener(e -> {
			//code inside here
		});



As you can see it can lead to many new possibilities to Java SE and Java EE developers.

Example code (this code displays a greeting to the screen with a functional interface):

interface Greeting {
	void sayHello(String name);
}

public class GreetingExample {

	public static void main(String[] args) {
		//Most efficient with lambdas
		greet(n->System.out.println("Hi " + n), "Kim");
		
		//Better way with lambdas
		Greeting greetingInstance = (name) -> System.out.println("Hi " + name);
		greet(greetingInstance, "Joe");
		
		//Old way without lambdas
		/*Greeting greetingInstance = new Greeting() {
			public void sayHello(String name) {
				System.out.println("Hello " + name + "!!!");
			}
		};
		greet(greetingInstance, "Sam");*/
	}
	
	public static void greet(Greeting greetingInstance, String name) {
		greetingInstance.sayHello(name);
	}

}



This should get you up and running :angel: .
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2