As a person java8 not particularly understand, we took a comprehensive read the next two weeks, "java8 combat" took notes a flowing water.
Java lines now are based java8 the future to make use of the characteristics of programmed java8.
What content is based on the markdown. . .
# Java8 combat
## by the code transfer behavior parameters 2
Parametric Behavior
a value of the parameter of
class 2, class anonymous, lambda
## 3 lambda expression
lambda expression
Comparator <Apple> byWeight = (Apple a1, Apple a2) -> a1.getWeight () compareTo (a2.getWeight ());.
function interface
defines only an abstract method
Functions descriptor
function interface signature is a signature abstract methods substantially Lambda expressions. We call this function is called abstract method descriptor.
(Apple, Apple) -> int
Only when necessary functional interface can transfer Lambda
Wraparound execution
try{}{
}
java predicate function interfaces of the formula
test(T t)
Functional Interface Consumer
Accept (T T)
Functional Interface Function
R & lt Apply (T T)
Abstract methods Supplier
T GET ()
Boxing and non-boxing
IntPredicate
IntConsume
int
Type checking function: function can be characterized in compliance with
Function variable does not recommend the use of local variables, plus the final use
Closure
Closure is an example of a function, and it can have unlimited access to non-local variables that function
Method references
Closure is an example of a function, and it can have unlimited access to the function of the non-local variables
The method of three references
a static method
A :: XX
2 directed to a method of any reference instance method
B: xx
method of Example 3, the conventional method of object reference
c: xx
构造函数引用
A::new
List<Integer> weights = Arrays.asList(7, 3, 4, 10);
List<Apple> apples = map(weights, Apple::new);
Array constructor and call the parent class
Automatically generating comparator
Comparator.comparing ((Apple a) -> a.getWeight ());
inventory.sort(comparing(Apple::getWeight).reversed());
inventory.sort(comparing(Apple::getWeight)
.reversed()
.thenComparing(Apple::getCountry));
Predicate谓词复合
Predicate<Apple> redAndHeavyAppleOrGreen =
readApple.and(a->a.getWeight() > b.getWeight())
.or(a -> "green".equals(a.getColor()));
function function compound
andthen, performed first, and then perform another function
first given as a function of the parameters that compose the function to the inside, and then the result for the function itself.
## 4 Flow
Defined flows
1 java API of
2 claims processing data set
3 advanced data iterator
Substantially defined stream
1 the sorted sequence of elements Map filter
2 source. Source:
3 data processing operations
filter the reduce Map Sort match Find
limit
. 4 line
5 internal iteration
The set stream
1 flows only traverse one
external iteration 2 is set, the flow of internal iterations
The operational flow
intermediate operating a
filter limit the sorted DISTINCT Map
2 operation is terminated
the collect
the foreach
COUNT
## 5 Using Flow
Screening predicate
filter
distinct
limit
skip
Mapping
the Map
flatMap
Find and match
allMatch AnyMatch noneMatch
findFirst findAny
optional操作
isPresent
ifPresent
T get()
T orElse(T other)
规约
reduce(init, func)
reduce(min/max)
count
所有的操作
filter
distinct
skip
limit
map
flatMap
sorted
anyMatch
noneMatch
allMatch
findAny
findFirst
forEach
collect
reduce
count
NUMERICAL
mapToInt
Boxed
IntStream.rangeClosed
构建流
stream.of();
stream.empty();
Arrays.stream(numes);
File.lines(
xxx).distinct().count
Function to create a stream
stream.iterate
Stream.generate
## collected data stream using 6
### 6.1 Collector & Statute Summary
The total number of
Collectors.counting ()
最大的 Collectors.maxBy(Comparator.comparingInt(Transaction::getValue))
Collectors.sumInt()
averagingInt
joining
reducie
redcing()
menu.stream().mapToInt(Dish::getCalories).sum();
### 6.2 Packet
groupingBy grouping, multi-level grouping
Subset of data collected by
The results are collected to be converted into another type collectAndThen
### 6.3 Partition
boolean word as the partition: partitioningBy
collection的静态方法
toList
toSet
toCollection
counting
summingint
averagingInt
joning
maxBy
minBy
reducing
collectionAndThen
groupingBy
partitioningBy
Collector Interface
自己实现java的stream
```
public interface Collector<T, A, R> {
Supplier<A> supplier();
BiConsumer<A, T> accumulator();
Function<A, R> finisher();
BinaryOperator<A> combiner();
Set<Characteristics> characteristics();
}
```
## 7 parallel data processing and properties
Parallel flow
parallel
Effect of parallel flow properties
1 and reduce the number of packing box
2 will affect the state variable shared parallel streams, and parallel computing.
If you have questions to be measured 3
4 parallel operation some poor linearity than
5 the total cost of the pipeline
when a smaller amount of data suited to 6
if a data structure is easily decomposed 7 behind
cost of merging step of intermediate 8
Source stream, decomposability
ArrayList excellent
LinkedList difference
IntStream.range excellent
Stream.iterate difference
HashSet Good
TreeSet Good
Branch / Merge framework
It implements ExecutorService interface assigns the task ForkJoinPool
task of achieving returns the result: RecursiveTask <R>
does not return results RecursiveAction
forkjoin business logic
`` `
IF (task sufficiently small or non-separable) {
sequentially calculates the task
} else {
task into two subtasks
recursive calls to this method, splitting each subtask and wait for all subtasks to complete
result of merging each subtask
}
` ` `
Best practices for using branching / merging the framework of
one pair join a task calls the method blocks the caller until the task is to make the result. Two tasks have begun to call after
2 ForkJoinPool invoke method should not be used in internal RecursiveTask. You should always call directly compute or fork method, only the sequential code to invoke it should start with parallel computing.
3 sub-task calls fork method it can be discharged into the ForkJoinPool.
4 debugging branching / merging of parallel computing framework can be somewhat tricky.
5 and parallel streams as granted that you should use branching / merging on the frame in a multi-core processor faster than the order of evaluation.
Principle steal
spliterator 可分迭代器
```
public interface Spliterator<T> {
boolean tryAdvance(Consumer<? super T> action);
Spliterator<T> trySplit();
long estimateSize();
int characteristics();
}
```
## 8 refactoring, testing and commissioning
Improved flexibility and can read and write
an anonymous class instead of using the lambda
2 stream method reference
3 is switched to stream
Code increase the flexibility of
a function using the interface
2 performs delay
3 surround performed
Reconstruction of design patterns using lambda
A strategy mode, the function interface
2
lambda expressions use
peek log debug stream
## 9 default method
Interface can use the default repeatedly
The method of the problem of conflict default interface
Class 1 and most
sub-optimal interfaces
3 shows the cover
## 10 Optional substituents null
create
Extracting
map data acquired inside Optional
flatMap acquired from another section Optional
GET
orElse
orElseGet
orElseThroww
The IfPresent
Filer filter
The detailed operation of
empty
filter
flatMap
GET
The IfPresent
isPresent
Map
of ofNullable orElse orElseGet orElseThrow
OptionalUtility Tools
## 11 CompletableFuture
future tool
`` `
ExecutorService Executor Executors.newCachedThreadPool = (); Future <Double> = executor.submit Future (a Callable new new <Double> () {
public Double Call () {
})
the try {
Double Future.get Result = (. 1, TimeUnit .SECONDS);
} the catch (ExecutionException EE) {// a calculated throw exception
} catch (InterruptedException ie) {// current thread is interrupted during the waiting
} catch (TimeoutException te) {// Future object before the completion of more than expired
}
`` `
Future limitations
. 1 Future difficult to directly express dependencies between a plurality of Future a result, development, we often need to achieve the following objectives:
2 merge two asynchronous computation (between two asynchronous computing a independently of each other, while the second turn depends on the result of a)
3 to wait for all the tasks are completed Future collection.
4 Future waiting only set the fastest end of the task is completed, and returns its result.
CompletableFuture
only when the complex needs of each operation takes a relatively long time
Basic Usage
`` `
Method Async ending all be executed asynchronously if the thread pool is specified, will perform in the specified thread pool, if not specified, the default will be executed ForkJoinPool.commonPool () in. Here are many ways are similar, no longer do otherwise stated.
Four static method used to create the object CompletableFuture piece of code asynchronous execution, the parameter type of the method is a function interface, so you can use a lambda expression to implement asynchronous tasks
runAsync Method: It Runnabel functional interface type parameter, the calculation result CompletableFuture is empty.
Methods supplyAsync Supplier <U> Function Interface Type parameter is calculated CompletableFuture result type is U.
`` `
```
public static CompletableFuture<Void> runAsync(Runnable runnable)
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
public <U> CompletionStage<U> thenApply(Function<? super T,? extends U> fn);
public <U> CompletionStage<U> thenApplyAsync(Function<? super T,? extends U> fn);
public <U> CompletionStage<U> thenApplyAsync(Function<? super T,? extends U> fn,Executor executor);
```
## 12 The new date and time API
The reason the new date appears library
The new date class
LocationDate LocationTime instant Duration period
Time range Period Duration
Operations and analytical
Calendar and time zones
13 functional thinking ##
Achieve and maintain
Class 1 rational structure
2 provides indicators
3 coupling, cohesion
Problem
variable data sharing
Imperative programming
Declarative Programming
name called problem
Programming function: a function programming mode
1 modified local variables
two reference objects unmodifiable
3 function or method not throw using Option <T>
Transparency cited: the same value, the output unchanged
Object-oriented and functional comparison of
an object things
2 referential transparency, there should not modify the object
When considering programming problem, a functional method, the input parameters and the output of attention function
recursive and iterative
functions for programming and does not contain while iterator
## 14 Functional Programming skills
### ubiquitous function
Higher order functions: at least one parameter function, a function return, attention functional side effects
Corey of: return function
Persistent data structure ###
The method can not modify the functional parameters or global parameters passed
### stream delay calculation?
stream allowed only once
stream does not allow recursive definition
Delayed List
### Pattern Matching
### Miscellaneous
Cache or memory table
a particular stream of
1.stream data is not stored
2.stream data source does not change
the delay of the execution characteristics 3.stream
## and 15 of object-oriented programming functions mixing
jvm platform functional language scala
scala programming better flow, better functional programming
## 16 Conclusions and future java
Try to use the new features