Lambdas
Anonymous classes are verbose and hard to use.
/**
* Java 8 Lambdas
*
* Anonymous class instance as a function object is ...
* hard to use.
*/
package com.minte9.effective.lambdas;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Anonymous {
public static void main(String[] args) {
List<String> words = new ArrayList<>();
words.add("ccc");
words.add("a");
words.add("bb");
Collections.sort(words,
new Comparator<String>() { // - Look Here
@Override public int compare(String s1, String s2) {
return Integer.compare(
s1.length(), s2.length()
);
}
}
);
words.forEach(System.out::println);
// a, bb, cc
}
}
Java 8 allows us to create instances of functional interfaces using lamdba expressions.
/**
* Java 8 Lambdas
*
* We create instances of functional interfaces using ...
* lamdba expressions.
*
* Lambdas are similar to anonymous classes, but ...
* more concise
*/
package com.minte9.effective.lambdas;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Lambdas {
public static void main(String[] args) {
List<String> words = new ArrayList<>();
words.add("ccc");
words.add("a");
words.add("bb");
// Example 1
Collections.sort(words,
(s1, s2) -> Integer.compare(s1.length(), s2.length())
);
words.forEach(System.out::println);
// a, bb, ccc
// Example 2
words.sort(
(s1, s2) -> Integer.compare(s1.length(), s2.length())
);
words.forEach(System.out::println);
// a, bb, ccc
}
}
Enums
Enum example with no lambdas.
/**
* Java 8 Lambdas
*
* Enum example with no Lambdas
*/
package com.minte9.effective.lambdas;
public class EnumsNoLambdas {
public enum Operation {
PLUS ('+') { public int run(int x, int y) { return x + y; } },
MINUS('-') { public int run(int x, int y) { return x - y; } },
;
private char ch;
private Operation(char ch) { this.ch = ch; }
public String toString() { return ch + ""; }
public abstract int run(int x, int y);
}
public static void main(String[] args) {
int a = Operation.PLUS.run(1, 2);
int b = Operation.MINUS.run(20, 10);
System.out.println(a); // 3
System.out.println(b); // 10
System.out.println(Operation.PLUS); // +
System.out.println(Operation.MINUS); // -
}
}
Enum example with lambdas.
/**
* Enum Example - With lambdas
*
* The constructor stores the lambda in an instanced field
* Later, the method run() invokes the lambda expression
*/
package com.minte9.effective.lambdas;
import java.util.function.IntBinaryOperator;
public class EnumLambdas {
public enum Operation {
PLUS ('+', (x, y) -> x + y) {},
MINUS ('-', (x, y) -> x - y) {};
IntBinaryOperator op;
private Operation(char ch, IntBinaryOperator op) { this.op = op; }
public int run(int x, int y) { return op.applyAsInt(x, y); }
}
public static void main(String[] args) {
int a = Operation.PLUS.run(1, 2);
int b = Operation.MINUS.run(20, 10);
System.out.println(a); // 3
System.out.println(b); // 10
}
}
Last update: 432 days ago