Comments (7)
Introduce Nested Classes
The Java programming language allows you to define a class within another class. Such a class is called a nested class and is illustrated here:
class OuterClass {
...
class NestedClass {
...
}
}
Terminology: Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes.
class OuterClass {
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass, a nested class can be declared private, public, protected, or package private. (Recall that outer classes can only be declared public or package private.)
Why Use Nested Classes?
Compelling reasons for using nested classes include the following:
-
It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
-
It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.
-
It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.
Static Nested Classes
As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.
Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
Inner Classes
As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.
Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:
An instance of InnerClass
can exist only within an instance of OuterClass
and has direct access to the methods and fields of its enclosing instance.
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
There are two special kinds of inner classes: local classes and anonymous classes.
Shadowing
If a declaration of a type (such as a member variable or a parameter name) in a particular scope (such as an inner class or a method definition) has the same name as another declaration in the enclosing scope, You cannot refer to a shadowed declaration by its name alone. The following example, ShadowTest, demonstrates this:
public class ShadowTest {
public int x = 0;
class FirstLevel {
public int x = 1;
void methodInFirstLevel(int x) {
System.out.println("x = " + x);
System.out.println("this.x = " + this.x);
System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
}
}
public static void main(String... args) {
ShadowTest st = new ShadowTest();
ShadowTest.FirstLevel fl = st.new FirstLevel();
fl.methodInFirstLevel(23);
}
}
The following is the output of this example:
x = 23
this.x = 1
ShadowTest.this.x = 0
This example defines three variables named x: the member variable of the class ShadowTest, the member variable of the inner class FirstLevel, and the parameter in the method methodInFirstLevel. The variable x defined as a parameter of the method methodInFirstLevel shadows the variable of the inner class FirstLevel. Consequently, when you use the variable x in the method methodInFirstLevel, it refers to the method parameter. To refer to the member variable of the inner class FirstLevel, use the keyword this to represent the enclosing scope:
System.out.println("this.x = " + this.x);
Refer to member variables that enclose larger scopes by the class name to which they belong. For example, the following statement accesses the member variable of the class ShadowTest from the method methodInFirstLevel:
System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
Summary
- Nested classes has two type :
static
andnot static
(but we also called it Inner Classes). - Inner Classes also has two type: 'Local Classes' and `Anonymous Classes'. We will see it late .
- We can Create StaticNested classes without create it outer class , but we can't use static class directly access it outer class , inner class is just the opposite.
- In Inner Classes we can't access shadowing variables , if we want to access , we should use that
ShadowTest
from blog.
Inner Class Example
To see an inner class in use, first consider an array. In the following example, you create an array, fill it with integer values, and then output only values of even indices of the array in ascending order.
The DataStructure.java example that follows consists of:
- The
DataStructure
outer class, which includes a constructor to create an instance of DataStructure containing an array filled with consecutive integer values (0, 1, 2, 3, and so on) and a method that prints elements of the array that have an even index value. - The EvenIterator inner class, which implements the DataStructureIterator interface, which extends the Iterator< Integer> interface. Iterators are used to step through a data structure and typically have methods to test for the last element, retrieve the current element, and move to the next element.
- A
main
method that instantiates a DataStructure object (ds), then invokes the printEven method to print elements of the array arrayOfInts that have an even index value.
public class DataStructure {
// Create an array
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];
public DataStructure() {
// fill the array with ascending integer values
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = i;
}
}
public void printEven() {
// Print out values of even indices of the array
DataStructureIterator iterator = this.new EvenIterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
System.out.println();
}
interface DataStructureIterator extends java.util.Iterator<Integer> { }
// Inner class implements the DataStructureIterator interface,
// which extends the Iterator<Integer> interface
private class EvenIterator implements DataStructureIterator {
// Start stepping through the array from the beginning
private int nextIndex = 0;
public boolean hasNext() {
// Check if the current element is the last in the array
return (nextIndex <= SIZE - 1);
}
public Integer next() {
// Record a value of an even index of the array
Integer retValue = Integer.valueOf(arrayOfInts[nextIndex]);
// Get the next even element
nextIndex += 2;
return retValue;
}
}
public static void main(String s[]) {
// Fill the array with integer values and print out only
// values of even indices
DataStructure ds = new DataStructure();
ds.printEven();
}
The output is:
0 2 4 6 8 10 12 14
Note that the EvenIterator class refers directly to the arrayOfInts instance variable of the DataStructure object.
You can use inner classes to implement helper classes such as the one shown in the this example. To handle user interface events, you must know how to use inner classes, because the event-handling mechanism makes extensive use of them.
Local and Anonymous Classes
There are two additional types of inner classes. You can declare an inner class within the body of a method. These classes are known as local classes. You can also declare an inner class within the body of a method without naming
the class. These classes are known as anonymous classes.
Modifiers
You can use the same modifiers for inner classes that you use for other members of the outer class. For example, you can use the access specifiers private, public, and protected to restrict access to inner classes, just as you use them to restrict access do to other class members.
from blog.
Local Classes
Local classes are classes that are defined in a block
, which is a group of zero or more statements between balanced braces. You typically find local classes defined in the body of a method.
Declaring Local Classes
You can define a local class inside any block . For example, you can define a local class in a method body, a for loop, or an if clause.
The following example, LocalClassExample, validates two phone numbers. It defines the local class PhoneNumber in the method validatePhoneNumber:
public class LocalClassExample {
static String regularExpression = "[^0-9]";
public static void validatePhoneNumber(
String phoneNumber1, String phoneNumber2) {
final int numberLength = 10;
// Valid in JDK 8 and later:
// int numberLength = 10;
class PhoneNumber {
String formattedPhoneNumber = null;
PhoneNumber(String phoneNumber){
// numberLength = 7;
String currentNumber = phoneNumber.replaceAll(
regularExpression, "");
if (currentNumber.length() == numberLength)
formattedPhoneNumber = currentNumber;
else
formattedPhoneNumber = null;
}
public String getNumber() {
return formattedPhoneNumber;
}
// Valid in JDK 8 and later:
// public void printOriginalNumbers() {
// System.out.println("Original numbers are " + phoneNumber1 +
// " and " + phoneNumber2);
// }
}
PhoneNumber myNumber1 = new PhoneNumber(phoneNumber1);
PhoneNumber myNumber2 = new PhoneNumber(phoneNumber2);
// Valid in JDK 8 and later:
// myNumber1.printOriginalNumbers();
if (myNumber1.getNumber() == null)
System.out.println("First number is invalid");
else
System.out.println("First number is " + myNumber1.getNumber());
if (myNumber2.getNumber() == null)
System.out.println("Second number is invalid");
else
System.out.println("Second number is " + myNumber2.getNumber());
}
public static void main(String... args) {
validatePhoneNumber("123-456-7890", "456-7890");
}
}
The example validates a phone number by first removing all characters from the phone number except the digits 0 through 9. After, it checks whether the phone number contains exactly ten digits (the length of a phone number in North America). This example prints the following:
First number is 1234567890
Second number is invalid
A local class has access to the members of its enclosing class. In the previous example, the PhoneNumber
constructor accesses the member LocalClassExample.regularExpression
.
In addition, a local class has access to local variables. However, a local class can only access local variables that are declared final. (I don't know why must declared variables to final ... I guess that's the reason for JVM).When a local class accesses a local variable or parameter of the enclosing block, it captures
that variable or parameter.For example, the PhoneNumber constructor can access the local variable numberLength because it is declared final; numberLength is a captured variable
.
However, starting in Java SE 8, a local class can access local variables and parameters of the enclosing block that are final or ·effectively final·. A variable or parameter whose value is never changed after it is initialized is effectively final. For example, suppose that the variable numberLength is not declared final, and you add the highlighted assignment statement in the PhoneNumber constructor:
PhoneNumber(String phoneNumber) {
numberLength = 7;
String currentNumber = phoneNumber.replaceAll(
regularExpression, "");
if (currentNumber.length() == numberLength)
formattedPhoneNumber = currentNumber;
else
formattedPhoneNumber = null;
}
Because of this assignment statement, the variable numberLength
is not effectively final anymore. As a result, the Java compiler generates an error message similar to "local variables referenced from an inner class must be final or effectively final" where the inner class PhoneNumber
tries to access the numberLength
variable:
if (currentNumber.length() == numberLength)
Starting in Java SE 8, if you declare the local class in a method, it can access the method's parameters. For example, you can define the following method in the PhoneNumber local class(I tried 1.5 and later version java , they all can run normal.So I think it may be a mistake in writing):
public void printOriginalNumbers() {
System.out.println("Original numbers are " + phoneNumber1 +
" and " + phoneNumber2);
}
The method printOriginalNumbers
accesses the parameters phoneNumber1
and phoneNumber2
of the method validatePhoneNumber
.
Summary
- Local class can access enclosing block variables or parameters.But the variables or parameters must be final or effectively final
- A variable or parameter whose value is never changed after it is initialized is effectively final.
- You cannot declare an interface inside a block; interfaces are inherently static
from blog.
Anonymous Classes
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
Declaring Anonymous Classes
While local classes are class declarations, anonymous classes are expressions, which means that you define the class in another expression. The following example, HelloWorldAnonymousClasses, uses anonymous classes in the initialization statements of the local variables frenchGreeting
and spanishGreeting
, but uses a local class for the initialization of the variable englishGreeting
:
public class HelloWorldAnonymousClasses {
interface HelloWorld {
void greet();
void greetSomeone(String someone);
}
public void sayHello() {
class EnglishGreeting implements HelloWorld {
String name = "world";
public void greet() {
greetSomeone("world");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Hello " + name);
}
}
HelloWorld englishGreeting = new EnglishGreeting();
HelloWorld frenchGreeting = new HelloWorld() {
String name = "tout le monde";
public void greet() {
greetSomeone("tout le monde");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Salut " + name);
}
};
HelloWorld spanishGreeting = new HelloWorld() {
String name = "mundo";
public void greet() {
greetSomeone("mundo");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Hola, " + name);
}
};
englishGreeting.greet();
frenchGreeting.greetSomeone("Fred");
spanishGreeting.greet();
}
public static void main(String... args) {
HelloWorldAnonymousClasses myApp =
new HelloWorldAnonymousClasses();
myApp.sayHello();
}
}
As mentioned previously, an anonymous class is an expression. The syntax of an anonymous class expression is like the invocation of a constructor, except that there is a class definition contained in a block of code.
Consider the instantiation of the frenchGreeting
object:
HelloWorld frenchGreeting = new HelloWorld() {
String name = "tout le monde";
public void greet() {
greetSomeone("tout le monde");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Salut " + name);
}
};
The anonymous class expression consists of the following:
- The
new
operator - The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface
HelloWorld
. - Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression.Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.
- A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.
Because an anonymous class definition is an expression, it must be part of a statement. In this example, the anonymous class expression is part of the statement that instantiates the frenchGreeting object. (This explains why there is a semicolon after the closing brace.)
Accessing Local Variables of the Enclosing Scope, and Declaring and Accessing Members of the Anonymous Class
Like local classes, anonymous classes can capture variables; they have the same access to local variables of the enclosing scope:
- An anonymous class has access to the members of its enclosing class.
- An anonymous class cannot access local variables in its enclosing scope that are not declared as
final
oreffectively final
. - Like a nested class, a declaration of a type (such as a variable) in an anonymous class shadows any other declarations in the enclosing scope that have the same name.
Anonymous classes also have the same restrictions as local classes with respect to their members:
- You cannot declare static initializers or member interfaces in an anonymous class.
- An anonymous class can have static members provided that they are constant variables.
Note that you can declare the following in anonymous classes:
- Fields
- Extra methods (even if they do not implement any methods of the supertype)
- Instance initializers
- Local classes
However, you cannot declare constructors in an anonymous class.
from blog.
Lambda Expressions
The previous section, Anonymous Classes, shows you how to implement a base class without giving it a name. Although this is often more concise than a named class, for classes with only one method, even an anonymous class seems a bit excessive and cumbersome. Lambda expressions let you express instances of single-method classes more compactly.
This section covers the following topics:
- Ideal Use Case for Lambda Expressions
- Approach 1: Create Methods That Search for Members That Match One Characteristic
- Approach 2: Create More Generalized Search Methods
- Approach 3: Specify Search Criteria Code in a Local Class
- Approach 4: Specify Search Criteria Code in an Anonymous Class
- Approach 5: Specify Search Criteria Code with a Lambda Expression
- Approach 6: Use Standard Functional Interfaces with Lambda Expressions
- Approach 7: Use Lambda Expressions Throughout Your Application
- Approach 8: Use Generics More Extensively
- Approach 9: Use Aggregate Operations That Accept Lambda Expressions as Parameters
- Lambda Expressions in GUI Applications
- Syntax of Lambda Expressions
- Accessing Local Variables of the Enclosing Scope
- Target Typing
- Target Types and Method Arguments
Ideal Use Case for Lambda Expressions
Suppose that you are creating a social networking application. You want to create a feature that enables an administrator to perform any kind of action, such as sending a message, on members of the social networking application that satisfy certain criteria.The following table describes this use case in detail:
Field | Description |
---|---|
Name | Perform action on selected members |
Primary Actor | Administrator |
Preconditions | Administrator is logged in to the system. |
Postconditions | Action is performed only on members that fit the specified criteria. |
Main Success Scenario | Administrator specifies criteria of members on which to perform a certain action.Administrator specifies an action to perform on those selected members.Administrator selects the Submit button.The system finds all members that match the specified criteria.The system performs the specified action on all matching members. |
Extensions | 1a. Administrator has an option to preview those members who match the specified criteria before he or she specifies the action to be performed or before selecting the Submit button. |
Frequency of Occurrence | Many times during the day. |
Suppose that members of this social networking application are represented by the following Person class , it's too long , so i will not show that in this.
Suppose that the members of your social networking application are stored in a List<Person>
instance.This section begins with a naive approach to this use case. It improves upon this approach with local and anonymous classes, and then finishes with an efficient and concise approach using lambda expressions. Find the code excerpts described in this section in the example RosterTest.
Approach 1: Create Methods That Search for Members That Match One Characteristic
One simplistic approach is to create several methods; each method searches for members that match one characteristic, such as gender or age. The following method prints members that are older than a specified age:
public static void printPersonsOlderThan(List<Person> roster, int age) {
for (Person p : roster) {
if (p.getAge() >= age) {
p.printPerson();
}
}
}
This approach can potentially make your application brittle
, which is the likelihood of an application not working because of the introduction of updates (such as newer data types). Suppose that you upgrade your application and change the structure of the Person class such that it contains different member variables; perhaps the class records and measures ages with a different data type or algorithm. You would have to rewrite a lot of your API to accommodate this change. In addition, this approach is unnecessarily restrictive; what if you wanted to print members younger than a certain age, for example?
Approach 2: Create More Generalized Search Methods
The following method is more generic than printPersonsOlderThan
; it prints members within a specified range of ages:
public static void printPersonsWithinAgeRange(
List<Person> roster, int low, int high) {
for (Person p : roster) {
if (low <= p.getAge() && p.getAge() < high) {
p.printPerson();
}
}
}
What if you want to print members of a specified sex, or a combination of a specified gender and age range? What if you decide to change the Person class and add other attributes such as relationship status or geographical location? Although this method is more generic than printPersonsOlderThan
, trying to create a separate method for each possible search query can still lead to brittle code. You can instead separate the code that specifies the criteria for which you want to search in a different class.
Approach 3: Specify Search Criteria Code in a Local Class
The following method prints members that match search criteria that you specify:
public static void printPersons(
List<Person> roster, CheckPerson tester) {
for (Person p : roster) {
if (tester.test(p)) {
p.printPerson();
}
}
}
This method checks each Person instance contained in the List parameter roster whether it satisfies the search criteria specified in the CheckPerson
parameter tester by invoking the method tester.test
. If the method tester.test
returns a true value, then the method printPersons
is invoked on the Person instance.
To specify the search criteria, you implement the CheckPerson interface:
interface CheckPerson {
boolean test(Person p);
}
The following class implements the CheckPerson
interface by specifying an implementation for the method test. This method filters members that are eligible for Selective Service in the United States: it returns a true
value if its Person parameter is male and between the ages of 18 and 25:
class CheckPersonEligibleForSelectiveService implements CheckPerson {
public boolean test(Person p) {
return p.gender == Person.Sex.MALE &&
p.getAge() >= 18 &&
p.getAge() <= 25;
}
}
To use this class, you create a new instance of it and invoke the printPersons
method:
printPersons(
roster, new CheckPersonEligibleForSelectiveService());
Although this approach is less brittle—you don't have to rewrite methods if you change the structure of the Person
—you still have additional code: a new interface and a local class for each search you plan to perform in your application. Because CheckPersonEligibleForSelectiveService
implements an interface, you can use an anonymous class instead of a local class and bypass the need to declare a new class for each search.
Approach 4: Specify Search Criteria Code in an Anonymous Class
One of the arguments of the following invocation of the method printPersons
is an anonymous class that filters members that are eligible for Selective Service in the United States: those who are male and between the ages of 18 and 25:
printPersons(
roster,
new CheckPerson() {
public boolean test(Person p) {
return p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25;
}
}
);
This approach reduces the amount of code required because you don't have to create a new class for each search that you want to perform. However, the syntax of anonymous classes is bulky considering that the CheckPerson
interface contains only one method. In this case, you can use a lambda expression instead of an anonymous class, as described in the next section.
Approach 5: Specify Search Criteria Code with a Lambda Expression
The CheckPerson
interface is a functional interface. A functional interface is any interface that contains only one abstract method. (A functional interface may contain one or more default methods or static methods.) Because a functional interface contains only one abstract method, you can omit the name of that method when you implement it. To do this, instead of using an anonymous class expression, you use a lambda expression, which is highlighted in the following method invocation:
printPersons(
roster,
(Person p) -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25
);
See Syntax of Lambda Expressions for information about how to define lambda expressions.
You can use a standard functional interface in place of the interface CheckPerson, which reduces even further the amount of code required.
Approach 6: Use Standard Functional Interfaces with Lambda Expressions
Reconsider the CheckPerson
interface:
interface CheckPerson {
boolean test(Person p);
}
This is a very simple interface. It's a functional interface because it contains only one abstract method. This method takes one parameter and returns a boolean value. The method is so simple that it might not be worth it to define one in your application. Consequently, the JDK defines several standard functional interfaces, which you can find in the package java.util.function
.
For example, you can use the Predicate<T>
interface in place of CheckPerson
. This interface contains the method boolean test(T t)
:
interface Predicate<T> {
boolean test(T t);
}
The interface Predicate<T>
is an example of a generic interface. Generic types (such as generic interfaces) specify one or more type parameters within angle brackets (<>). This interface contains only one type parameter, T. When you declare or instantiate a generic type with actual type arguments, you have a parameterized type. For example, the parameterized type Predicate<Person>
is the following:
interface Predicate<Person> {
boolean test(Person t);
}
This parameterized type contains a method that has the same return type and parameters as CheckPerson.boolean test(Person p)
. Consequently, you can use Predicate in place of CheckPerson as the following method demonstrates:
public static void printPersonsWithPredicate(
List<Person> roster, Predicate<Person> tester) {
for (Person p : roster) {
if (tester.test(p)) {
p.printPerson();
}
}
}
As a result, the following method invocation is the same as when you invoked printPersons
in Approach 3: Specify Search Criteria Code in a Local Class to obtain members who are eligible for Selective Service:
printPersonsWithPredicate(
roster,
p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25
);
This is not the only possible place in this method to use a lambda expression. The following approach suggests other ways to use lambda expressions.
Reconsider the method ·printPersonsWithPredicate` to see where else you could use lambda expressions:
public static void printPersonsWithPredicate(
List<Person> roster, Predicate<Person> tester) {
for (Person p : roster) {
if (tester.test(p)) {
p.printPerson();
}
}
}
This method checks each Person instance contained in the List
parameter roster
whether it satisfies the criteria specified in the Predicate
parameter tester
. If the Person instance does satisfy the criteria specified by tester
, the method printPersron
is invoked on the Person
instance.
Instead of invoking the method printPerson
, you can specify a different action to perform on those Person
instances that satisfy the criteria specified by tester
.You can specify this action with a lambda expression. Suppose you want a lambda expression similar to printPerson, one that takes one argument (an object of type Person) and returns void.Remember, to use a lambda expression, you need to implement a functional interface. In this case, you need a functional interface that contains an abstract method that can take one argument of type Person
and returns void. The Consumer<T>
interface contains the method void accept(T t)
, which has these characteristics. The following method replaces the invocation p.printPerson()
with an instance of Consumer<Person>
that invokes the method accept:
public static void processPersons(
List<Person> roster,
Predicate<Person> tester,
Consumer<Person> block) {
for (Person p : roster) {
if (tester.test(p)) {
block.accept(p);
}
}
}
As a result, the following method invocation is the same as when you invoked printPersons in Approach 3: Specify Search Criteria Code in a Local Class to obtain members who are eligible for Selective Service. The lambda expression used to print members is highlighted:
processPersons(
roster,
p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25,
p -> p.printPerson() // note that !!!
);
What if you want to do more with your members' profiles than printing them out. Suppose that you want to validate the members' profiles or retrieve their contact information? In this case, you need a functional interface that contains an abstract method that returns a value.The Function<T,R>
interface contains the method R apply(T t)
. The following method retrieves the data specified by the parameter mapper
,and then performs an action on it specified by the parameter block
:
public static void processPersonsWithFunction(
List<Person> roster,
Predicate<Person> tester,
Function<Person, String> mapper,
Consumer<String> block) {
for (Person p : roster) {
if (tester.test(p)) {
String data = mapper.apply(p);
block.accept(data);
}
}
}
The following method retrieves the email address from each member contained in roster
who is eligible for Selective Service and then prints it:
processPersonsWithFunction(
roster,
p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25,
p -> p.getEmailAddress(),
email -> System.out.println(email)
);
Approach 8: Use Generics More Extensively
Reconsider the method processPersonsWithFunction
. 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);
}
}
}
To print the e-mail address of members who are eligible for Selective Service, invoke the processElements
method as follows:
processElements(
roster,
p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25,
p -> p.getEmailAddress(),
email -> System.out.println(email)
);
This method invocation performs the following actions:
- Obtains a source of objects from the collection source. In this example, it obtains a source of Person objects from the collection roster. Notice that the collection roster, which is a collection of type List, is also an object of type Iterable.
- Filters objects that match the Predicate object tester. In this example, the Predicate object is a lambda expression that specifies which members would be eligible for Selective Service.
- Maps each filtered object to a value as specified by the Function object mapper. In this example, the Function object is a lambda expression that returns the e-mail address of a member.
- Performs an action on each mapped object as specified by the Consumer object block. In this example, the Consumer object is a lambda expression that prints a string, which is the e-mail address returned by the Function object.
You can replace each of these actions with an aggregate operation.
Approach 9: Use Aggregate Operations That Accept Lambda Expressions as Parameters
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));
The following table maps each of the operations the method processElements performs with the corresponding aggregate operation:
processElements Action | Aggregate Operation |
---|---|
Obtain a source of objects | Stream stream() |
Filter objects that match a Predicate object | Stream filter(Predicate<? super T> predicate) |
Map objects to another value as specified by a Function object | Stream map(Function<? super T,? extends R> mapper) |
Perform an action as specified by a Consumer object | void forEach(Consumer<? super T> action) |
The operations filter, map, and forEach are aggregate operations
. Aggregate operations process elements from a stream, not directly from a collection (which is the reason why the first method invoked in this example is stream
). A stream
is a sequence of elements.
Unlike a collection, it is not a data structure that stores elements. Instead, a stream carries values from a source, such as collection, through a pipeline. A pipeline is a sequence of stream operations, which in this example is filter- map-forEach. In addition, aggregate operations typically accept lambda expressions as parameters, enabling you to customize how they behave.
For a more thorough discussion of aggregate operations, see the Aggregate Operations lesson.
Syntax of Lambda Expressions
A lambda expression consists of the following:
- A comma-separated list of formal parameters enclosed in parentheses. The
CheckPerson.test
method contains one parameter,p
, which represents an instance of thePerson
class.
Note: You can omit the data type of the parameters in a lambda expression. In addition, you can omit the parentheses if there is only one parameter. For example, the following lambda expression is also valid:
p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25
- The arrow token,
->
- A body, which consists of a single expression or a statement block. This example uses the following expression:
p -> {
return p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25;
}
A return statement is not an expression; in a lambda expression, you must enclose statements in braces ({}). However, you do not have to enclose a void method invocation in braces. For example, the following is a valid lambda expression:
email -> System.out.println(email)
Note that a lambda expression looks a lot like a method declaration; you can consider lambda expressions as anonymous methods—methods without a name.
The following example, Calculator, is an example of lambda expressions that take more than one formal parameter:
public class Calculator {
interface IntegerMath {
int operation(int a, int b);
}
public int operateBinary(int a, int b, IntegerMath op) {
return op.operation(a, b);
}
public static void main(String... args) {
Calculator myApp = new Calculator();
IntegerMath addition = (a, b) -> a + b;
IntegerMath subtraction = (a, b) -> a - b;
System.out.println("40 + 2 = " +
myApp.operateBinary(40, 2, addition));
System.out.println("20 - 10 = " +
myApp.operateBinary(20, 10, subtraction));
}
}
The method operateBinary
performs a mathematical operation on two integer operands. The operation itself is specified by an instance of IntegerMath
. The example defines two operations with lambda expressions, addition and subtraction. The example prints the following:
40 + 2 = 42
20 - 10 = 10
Accessing Local Variables of the Enclosing Scope
Like local and anonymous classes, lambda expressions can capture variables
;they have the same access to local variables of the enclosing scope. However, unlike local and anonymous classes, lambda expressions do not have any shadowing issues.Lambda expressions are lexically scoped.This means that they do not inherit any names from a supertype or introduce a new level of scoping. Declarations in a lambda expression are interpreted just as they are in the enclosing environment. The following example, LambdaScopeTest
, demonstrates this:
import java.util.function.Consumer;
public class LambdaScopeTest {
public int x = 0;
class FirstLevel {
public int x = 1;
void methodInFirstLevel(int x) {
// The following statement causes the compiler to generate
// the error "local variables referenced from a lambda expression
// must be final or effectively final" in statement A:
//
// x = 99;
Consumer<Integer> myConsumer = (y) ->
{
System.out.println("x = " + x); // Statement A
System.out.println("y = " + y);
System.out.println("this.x = " + this.x);
System.out.println("LambdaScopeTest.this.x = " +
LambdaScopeTest.this.x);
};
myConsumer.accept(x);
}
}
public static void main(String... args) {
LambdaScopeTest st = new LambdaScopeTest();
LambdaScopeTest.FirstLevel fl = st.new FirstLevel();
fl.methodInFirstLevel(23);
}
}
This example generates the following output:
x = 23
y = 23
this.x = 1
LambdaScopeTest.this.x = 0
If you substitute the parameter x
in place of y
in the declaration of the lambda expression myConsumer
, then the compiler generates an error:
Consumer<Integer> myConsumer = (x) -> {
// ...
}
**The compiler generates the error "variable x is already defined in method methodInFirstLevel(int)" because the lambda expression does not introduce a new level of scoping.**Consequently, you can directly access fields, methods, and local variables of the enclosing scope. For example, the lambda expression directly accesses the parameter x
of the method methodInFirstLevel
. To access variables in the enclosing class, use the keyword this
. In this example, this.x refers to the member variable FirstLevel.x
.
However, like local and anonymous classes, a lambda expression can only access local variables and parameters of the enclosing block that are final or effectively final. For example, suppose that you add the following assignment statement immediately after the methodInFirstLevel
definition statement:
void methodInFirstLevel(int x) {
x = 99;
// ...
}
Because of this assignment statement, the variable FirstLevel.x
is not effectively final anymore. As a result, the Java compiler generates an error message similar to "local variables referenced from a lambda expression must be final or effectively final" where the lambda expression myConsumer
tries to access the FirstLevel.x
variable:
System.out.println("x = " + x);
Summary
- Lambda expressions let you express instances of single-method classes more compactly.
- Lambda expressions do not have any shadowing issues , because they do not inherit any names from a supertype or introduce a new level of scoping.
- Use
{}
stanx , we must declare return key word . - We can use
Predicate<T>
to do simplytest
. - Study Aggregate Operations
- A functional interface is any interface that contains only one abstract method.
from blog.
Method References
You use lambda expressions to create anonymous methods. Sometimes, however, a lambda expression does nothing but call an existing method. In those cases, it's often clearer to refer to the existing method by name. Method references enable you to do this; they are compact, easy-to-read lambda expressions for methods that already have a name.
Consider again the Person class discussed in the section Lambda Expressions:
public class Person {
public enum Sex {
MALE, FEMALE
}
String name;
LocalDate birthday;
Sex gender;
String emailAddress;
public int getAge() {
// ...
}
public Calendar getBirthday() {
return birthday;
}
public static int compareByAge(Person a, Person b) {
return a.birthday.compareTo(b.birthday);
}}
Suppose that the members of your social networking application are contained in an array, and you want to sort the array by age. You could use the following code (find the code excerpts described in this section in the example MethodReferencesTest):
List<Person> roster = createRoster();
Person[] rosterAsArray = roster.toArray(new Person[roster.size()]);
class PersonAgeComparator implements Comparator<Person> {
public int compare(Person a, Person b) {
return a.getBirthday().compareTo(b.getBirthday());
}
}
Arrays.sort(rosterAsArray, new PersonAgeComparator());
The method signature of this invocation of sort
is the following:
static <T> void sort(T[] a, Comparator<? super T> c)
Notice that the interface Comparator
is a functional interface. Therefore, you could use a lambda expression instead of defining and then creating a new instance of a class that implements Comparator
:
Arrays.sort(rosterAsArray,
(Person a, Person b) -> {
return a.getBirthday().compareTo(b.getBirthday());
}
)
However, this method to compare the birth dates of two Person instances already exists as Person.compareByAge
. You can invoke this method instead in the body of the lambda expression:
Arrays.sort(rosterAsArray,
(a, b) -> Person.compareByAge(a, b)
);
By the way , that lambda can replace with
Comparator.comparing(a -> a.getBirthday())
,
Because this lambda expression invokes an existing method, you can use a method reference instead of a lambda expression:
Arrays.sort(rosterAsArray, Person::compareByAge);
The method reference Person::compareByAge
is semantically the same as the lambda expression (a, b) -> Person.compareByAge(a, b)
.
Kinds of Method References
There are four kinds of method references:
Kind | Example |
---|---|
Reference to a static method | ContainingClass::staticMethodName |
Reference to an instance method of a particular object | containingObject::instanceMethodName |
Reference to an instance method of an arbitrary object of a particular type | ContainingType::methodName |
Reference to a constructor | ClassName::new |
Reference to a Static Method
The method reference Person::compareByAge
is a reference to a static method.
Reference to an Instance Method of a Particular Object
The following is an example of a reference to an instance method of a particular object:
static class ComparisonProvider {
public int compareByName(Person a, Person b) {
return a.getName().compareTo(b.getName());
}
public int compareByAge(Person a, Person b) {
return a.getBirthday().compareTo(b.getBirthday());
}
}
public static void main(String[] args) {
List<Person> roster = createRoster();
Person[] rosterAsArray = roster.toArray(new Person[roster.size()]);
ComparisonProvider myComparisonProvider = new ComparisonProvider();
Arrays.sort(rosterAsArray, myComparisonProvider::compareByName);
}
The method reference myComparisonProvider::compareByName
invokes the method compareByName
that is part of the object myComparisonProvider
. The JRE infers the method type arguments, which in this case are (Person, Person)
.
Reference to an Instance Method of an Arbitrary Object of a Particular Type
The following is an example of a reference to an instance method of an arbitrary object of a particular type:
String[] stringArray = { "Barbara", "James", "Mary", "John",
"Patricia", "Robert", "Michael", "Linda" };
Arrays.sort(stringArray, String::compareToIgnoreCase);
The equivalent lambda expression for the method reference String::compareToIgnoreCase
would have the formal parameter list (String a, String b)
, where a and b are arbitrary names used to better describe this example. The method reference would invoke the method a.compareToIgnoreCase(b)
.
Reference to a Constructor
You can reference a constructor in the same way as a static method by using the name new
. The following method copies elements from one collection to another:
public static <T, SOURCE extends Collection<T>, DEST extends Collection<T>>
DEST transferElements(
SOURCE sourceCollection,
Supplier<DEST> collectionFactory) {
DEST result = collectionFactory.get();
for (T t : sourceCollection) {
result.add(t);
}
return result;
}
The functional interface Supplier
contains one method get that takes no arguments and returns an object. Consequently, you can invoke the method transferElements
with a lambda expression as follows:
Set<Person> rosterSetLambda = transferElements(roster, () -> new HashSet<>());
You can use a constructor reference in place of the lambda expression as follows:
Set<Person> rosterSet = transferElements(roster, HashSet::new);
The Java compiler infers that you want to create a HashSet
collection that contains elements of type Person
. Alternatively, you can specify this as follows:
Set<Person> rosterSet = transferElements(roster, HashSet<Person>::new);
from blog.
Done 🎉
from blog.
Related Issues (20)
- Explore the world of IOS / OSX developers HOT 1
- Ssh Passwordless Login
- CircleCi direct deploy app to server by ssh
- The high-quality TypeScript Declaration File.
- 把博客迁移到 Next.js HOT 3
- 98 HOT 1
- Mobx + useContext + ts = !!!! HOT 5
- 直接在微信内查看pdf文件的方法
- bilibili 出黑暗模式了 !!! HOT 2
- 弹窗设计思考
- circleci + jest + codecov 实现代码覆盖率统计
- SWR 不完全指南
- 理解 React Suspense
- 在Flutter里面使用Debounce函数
- Flutter 给IOS数字键盘加上完成按钮
- Flutter 开发体验汇总
- Typescript 动态枚举类型 (或者叫做限定类型) HOT 4
- Flutter 限制TextField 只允许输入小数
- 依赖反转原则
- Linux Tools Quick Tutorial Basic part
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from blog.