Effective Java 3/E summary chanpter 3 (Shorter version)
28 Dec 2020Chanpter 6 : Lambda and Stream
You can find the longer version of this summary here.
- Java 8, Android API 24 or higher
Lambda
- Use Lambda instaed of an anonymous class
- Anonymous class < Lambda < Method reference
- If the readability seems to be poor, use Lambda instaed of Method reference
- Standard functional interface (java.util.function)
- 43 in total : 6 basic types can be extended
UnaryOperator: 1 argument, argument type = return typeBinaryOperator: 2 arguments, argument type = return typePredicate: 1 argument, return booelanFunction: 1 argument, argument type != return typeSupplier: Returns a value without argumentsConsumer: 1 argument, return void- Transform 3 pieces each for
int,long, anddouble - 9 transformations from
Functionto SrcToRes - transformation that takes 2 arguments (
Predicate,Function,Consumer) - 2 arguments + return basic type
Fuction - 1 argument + argument basic type
Consumer Supplierthat returns Boolean
- 43 in total : 6 basic types can be extended
Stream
- Replace loop (
for,while) - Change the loop to
Streamand consider readability - Cannot be changed to
Streamwhen- local variables need to be modified
return,break,continue,exceptionis implemented
- Use
java.util.stream.Collectorsmethods for reducing side-effectstoList,toSet,toMap,groupingBy,joining
- Best return type is
Collection!Collectioncan be both (Iterable, Stream).- Tremendous sequence can be replaced to
AbstractCollecion.
- For
parallel(), consider whether (the number of elements * the number of implemented codes > Hundreds of thousands)