New Features in JDK 8: Ivan St. Ivanov Dmitry Alexandrov Martin Toshev
New Features in JDK 8: Ivan St. Ivanov Dmitry Alexandrov Martin Toshev
• Lambda Expressions
• Example:
(x,y) -> x + y
Lambdas
• Lambdas bring anonymous function types in Java
• Example:
(x,y) -> x + y
• Environment setup
• Concept
• Task categories
Lambdas Hands-on-Lab:
Environment Setup
o Eclipse
http://www.oracle.com/technetwork/articles/java/lambda-
1984522.html
(for Eclipse 4.3: Start IDE -> Install New Software)
http://build.eclipse.org/eclipse/builds/4P/siteDir/updates/4.3-P-
builds
o IntelliJ IDEA CE
http://www.jetbrains.com/idea/free_java_ide.html
Lambdas Hands-on-Lab:
Environment Setup
• Get the sources:
• Mapping
• Method References
Lambdas Hands-on-Lab:
Internal vs External Iteration
Java 7 (External)
Java 8 (Internal)
myShapes.forEach(shape ->
shape.setColor(RED));
Lambdas Hands-on-Lab:
Filtering and Collecting
Java7
for (String s: otherThings) {
if (satisfiesSomeCondition(s)) {
things.add(s);
}
}
Java8
otherThings.stream()
.filter(s ->
satisfiesSomeCondition(s))
.collect(Collectors.toList());
Lambdas Hands-on-Lab:
Mapping
Java7
List<String> upperCaseStrings = new ArrayList<>();
for (String s: mixedCaseStrings) {
upperCaseStrings.add(s.toUpperCase());
}
Java8
mixedCaseStrings.stream()
.map(s -> s.toUpperCase())
.collect(Collectors.toList());
Lambdas Hands-on-Lab:
Mapping
Using a lambda expression:
myStrings.map(String::toUpperCase);
public interface A {
default void foo(){
System.out.println("Calling A.foo()");
}
}
Method method = …
Parameter param = method.getParameters()[0];
System.out.println(param.getName());
Annotation on Java Types
(JSR 308, JEP 104)
• Extend the set of annotatable locations in the
syntax of the Java programming language
Lambda FAQ
http://www.lambdafaq.org/
References
Java SE tutorials: Lambda Expressions
http://docs.oracle.com/javase/tutorial/java/javaOO
/lambdaexpressions.html