⇤ ← Revision 1 as of 2016-06-25 17:52:05
Size: 1066
Comment:
|
Size: 2212
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 32: | Line 32: |
== Method reference examples == {{{#!highlight java /* Usage of :: to refer to a method. Similar in concept to function pointers/callbacks javac MethodReferenceExample.java ASD.java java -cp . MethodReferenceExample Interface Consumer<T> Functional interface and can therefore be used as the assignment target for a lambda expression or method reference. */ import java.util.ArrayList; public class MethodReferenceExample{ public static void main(String[] args){ System.out.println("MethodReferenceExample"); ArrayList<String> al = new ArrayList<String>(); al.add("Str1"); al.add("Str2"); al.add("Str3"); //For each string in the array list call println having as argument the item al.forEach(System.out::println); ASD dummy = new ASD(); al.forEach(dummy::showStuff); } } }}} {{{#!highlight java public class ASD{ public ASD(){ } public void showStuff(String message){ System.out.println("Show stuff " + message); } } }}} |
Java8
Has many improvments like added support for functional programming, added new date time API and the new stream API similar to LINQ queries in C# (map/reduce).
Lambda expressions examples
1 /*
2 javac LambdaExpressionTest.java
3 java -cp . LambdaExpressionTest
4 */
5 public class LambdaExpressionTest{
6 public static void main(String[] args){
7 System.out.println("LambdaExpressionTest");
8 // define implementation
9 // (lambda parameters) -> { // lambda body };
10 TestIt testIt = (stuffx) -> System.out.println("Stuff " + stuffx);
11 testIt.sayStuff("Msg");
12
13 // change lambda function implementation
14 testIt = (stuffxx) -> {
15 stuffxx = stuffxx.toUpperCase();
16 System.out.println("OtherStuff " + stuffxx);
17 };
18 testIt.sayStuff("Msg");
19 }
20
21 // lambda expressions require interfaces to define the expected parameters
22 public interface TestIt{
23 void sayStuff(String stuff);
24 }
25 }
Method reference examples
1 /*
2 Usage of :: to refer to a method. Similar in concept to function pointers/callbacks
3
4 javac MethodReferenceExample.java ASD.java
5 java -cp . MethodReferenceExample
6
7 Interface Consumer<T>
8 Functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
9 */
10
11 import java.util.ArrayList;
12
13 public class MethodReferenceExample{
14 public static void main(String[] args){
15 System.out.println("MethodReferenceExample");
16 ArrayList<String> al = new ArrayList<String>();
17 al.add("Str1");
18 al.add("Str2");
19 al.add("Str3");
20
21 //For each string in the array list call println having as argument the item
22 al.forEach(System.out::println);
23 ASD dummy = new ASD();
24 al.forEach(dummy::showStuff);
25 }
26 }