Java Reference
In-Depth Information
in the StringToIntMapper interface; finally, it infers that the type of the lambda expression is the StringToIntMapper
interface type. When you call the map() method on the mapper variable passing a String , the body of the lambda
expression is executed as shown in the following snippet of code:
StringToIntMapper mapper = (String str) -> str.length();
String name = "Kristy";
int mappedValue = mapper.map(name);
System.out.println("name=" + name + ", mapped value=" + mappedValue);
name=Kristy, mapped value=6
So far, you have not seen anything that you could not do in Java without using lambda expressions. The following
snippet of code uses an anonymous class to achieve the same result as the lambda expression used in the previous
example:
StringToIntMapper mapper = new StringToIntMapper() {
@Override
public int map(String str) {
return str.length();
}
};
String name = "Kristy";
int mappedValue = mapper.map(name);
System.out.println("name=" + name + ", mapped value=" + mappedValue);
name=Kristy, mapped value=6
At this point, a lambda expression may seem to be a concise way of writing an anonymous class, which is true as
far as the syntax goes. There are some subtle differences in semantics between the two. I will discuss the differences
between a lambda expressions and anonymous classes as I discuss more details later.
Java is a strongly-typed language, which means that the compiler must know the type of all expressions used
in a Java program. a lambda expression by itself does not have a type, and therefore, it cannot be used as a standalone
expression. the type of a lambda expression is always inferred by the compiler by the context in which it is used.
Tip
Why Do We Need Lambda Expressions?
Java has supported object-oriented programming since the beginning. In object-oriented programming, the program
logic is based on mutable objects. Methods of classes contain the logic. Methods are invoked on objects, which
typically modify their states. In object-oriented programming, the order of method invocation matters as each method
invocation may potentially modify the state of the object, thus producing side effects. Static analysis of the program
logic is difficult as the program state depends on the order in which the code will be executed. Programming with
mutating objects also poses a challenge in concurrent programming in which multiple parts of the program may
attempt to modify the state of the same object concurrently. As the processing power of computers has increased
in recent years, so has the amount of data to be processed. Nowadays, it is not uncommon to process data as big as
terabytes in size, requiring the need for parallel programming. Now it is common for computers to have a multi-core
processor that give users the opportunity to run software programs faster; at the same time, this poses a challenge to
 
 
Search WWH ::




Custom Search