"Java 8 in Action" Chapter 4: introduction flow

1. Introduction Flow

Flow is a new member of the Java API, which allows you to declarative approach to data collection (expressed by the query, rather than temporary write an implementation). For now, you can think of them as to traverse the data set high-level iterators. In addition, the stream may also be transparently processed in parallel. Let's look at an example of a low-calorie return (<400) dishes Name:

Java7版本:
List<Dish> lowCaloricDishes = new ArrayList<>();
// 用累加器筛选元素
for(Dish d: menu){
    if(d.getCalories() < 400){
        lowCaloricDishes.add(d);
    }
}
// 用匿名类对菜肴排序
Collections.sort(lowCaloricDishes, new Comparator<Dish>() {
    public int compare(Dish d1, Dish d2){
        return Integer.compare(d1.getCalories(), d2.getCalories());
    }
});
// 处理排序后的菜名列表
List<String> lowCaloricDishesName = new ArrayList<>();
for(Dish d: lowCaloricDishes){
    lowCaloricDishesName.add(d.getName());
}
Java8版本:
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
List<String> lowCaloricDishesName = menu.stream()
                                        .filter(d -> d.getCalories() < 400)    // 选出400卡路里以下的菜肴
                                        .sorted(comparing(Dish::getCalories))    // 按照卡路里排序
                                        .map(Dish::getName)                    // 提取菜肴名称
                                        .collect(toList());                    // 将所有的名称保存在List中
利用多核架构并行执行,只需要把stream()换成parallelStream()

Java 8 in the Stream API features:

  • Declarative - more concise and easier to read
  • Can be complex - more flexible
  • Parallel - better performance

Flow definition:

  • Sequence elements - as just set, the flow also provides an interface to access an ordered set of values ​​of a particular element type.
  • Source - providing a source stream of data will be used, such as a set, or array input / output resources. Please note that preserves the original order when the stream is generated from an ordered collection. Flow generated by the list, which is consistent with the order of elements in the list.
  • Data processing operation - the stream data processing function is similar to support operation of the database, as well as functional programming languages ​​commonly used operations, such as filter, map, reduce, find, match, sort the like. Streaming operations may be performed sequentially, it may be performed in parallel.
  • Line - a lot of flow operation itself will return a stream, so that multiple operations can be linked together to form a big line. This allows some optimization of our next chapter as possible, as delays and short circuit. Pipeline operation can be seen as the data source database type queries.
  • Internal iterations - the set explicit iterators different iterations iterative operational flow is carried out behind.

2. flow and collections

Differences between sets is that when the flow calculation. A collection is an in-memory data structure, which contains data structures in all current values ​​- a set of each element had first worked out in order to add to the collection. In contrast, the stream is conceptually fixed data structures (you can not add or delete elements), which is the demand computing elements. Another key difference is that the set and the way they traverse the flow of data.

2.1 traversed only once

And iterators similar to flow only traversed once. After walking, we say that the stream has been consumed. The following code will throw an exception indicating that the stream has been consumed:

List<String> title = Arrays.asList(“Java8”,”In”, “Action”);
Stream<String> s = title.stream();
s.forEach(System.out::println);
s.forEach(System.out::println);

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
    at java.util.stream.AbstractPipeline.sourceStageSpliterator(AbstractPipeline.java:279)
    at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
    at com.lujiahao.learnjava8.chapter4.StreamAndCollection.main(StreamAndCollection.java:16)

2.2 External and internal iteration Iteration

Use the Collection interface requires the user to do an iterative (such as using for-each), which called external iteration. Instead, Streams library uses internal iteration

集合:用for-each循环外部迭代
List<String> names = new ArrayList<>();
for(Dish d: menu){
    names.add(d.getName());
}

集合:用背后的迭代器做外部迭代
List<String> names = new ArrayList<>();
Iterator<String> iterator = menu.iterator();
while(iterator.hasNext()) {
    Dish d = iterator.next();
    names.add(d.getName());
}

流:内部迭代
List<String> names = menu.stream()
                        .map(Dish::getName)
                        .collect(toList());

3. Operation Flow

java.util.stream.Stream Stream interface defines the number of operations. They can be divided into two categories. Flow operation may be called an intermediate connecting operation, the closing operation of the stream is referred to as terminal operation.
Intermediate operations: Unless trigger a terminal operation on the assembly line, otherwise the operation does not perform any intermediate processing.
Terminal operation: generates a result from the pipeline flow. As a result, any value not flow.

Using streams generally include three things:

  • A data source (e.g., set) to execute a query;
  • An intermediate chain operation, a stream pipeline is formed;
  • A terminal operation, execution pipeline, and to generate results.

The idea behind the pipeline flow is similar to building mode.

Common stream operation:

4. Summary

The following are some of the key concepts in this chapter to the school you should.

  • Flow is "generated from the source supports a series of elements of the data processing operation."
  • Stream using internal iterations: Iteration through filter, map, sorted out other operations are abstracted.
  • Operation flow of two types: terminal operation and intermediate operation.
  • filter map and other intermediate operation returns a stream, and can be linked together. They can be used to set a line, but does not produce any results
  • forEach, and count operation of the terminal returns a non-flow value, and returns the result to the processing pipeline.
  • Demand flow element is calculated.

Resources

  • No public replies: Java8 can get "Java 8 in Action" in the English version!

Tips

  • Welcome to the collection and forwarding, thank you for your support! (1 • ㅂ •) و✧
  • I welcome the attention of the public number: zhuangli program ape, reading notes tutorial resources for the first time to obtain!

Guess you like

Origin www.cnblogs.com/HelloDeveloper/p/11406903.html