Java:Lambda
Functional Interface
functional interface – an interface with a single abstract method. The Java API has many one-method interfaces such as Runnable, Callable, Comparator, ActionListener and others. They can be implemented and instantiated using anonymous class syntax.
Labmda expression
public interface Hello {
public void sayHello(String who);
}
public interface Print<T> {
public void print(T msg);
}
public static void main(String[] args) {
Hello h = (String s) -> System.out.println(s);
h.sayHello("Riguz");
Print<Float> p = (f) -> {
System.out.println(f);
System.out.println("Labmda");
};
p.print(new Float(3.1415926f));
}
Aggregate operations
The following is a generic version of it that accepts, as a parameter, a collection that contains elements of any data type:
public static <X, Y> void processElements(
Iterable<X> source,
Predicate<X> tester,
Function <X, Y> mapper,
Consumer<Y> block) {
for (X p : source) {
if (tester.test(p)) {
Y data = mapper.apply(p);
block.accept(data);
}
}
}
The following example uses aggregate operations to print the e-mail addresses of those members contained in the collection roster who are eligible for Selective Service:
roster
.stream()
.filter(
p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25)
.map(p -> p.getEmailAddress())
.forEach(email -> System.out.println(email));
Aggregate Operation |
---|
Stream<E> stream() |
Stream<T> filter(Predicate<? super T> predicate) |
<R> Stream<R> map(Function<? super T,? extends R> mapper) |
void forEach(Consumer<? super T> action) |