Java8 new Features Chapter 3rd (Stream API)

Source: Internet
Author: User
Tags getcolor stream api

Stream as one of the new features of Java8, he and InputStream and OutputStream in the Java IO Package are not a concept at all. Stream in Java8 is an enhancement to the collection's functionality and is primarily used to perform a variety of very convenient and efficient aggregation and mass data operations on collection objects. The combination of lambda expressions can greatly improve development efficiency and code readability.

Suppose we need to set all the shapes in a set to red, so we can write

for (Shape shape : shapes){    shape.setColor(RED)}

If you use the JAVA8 Extended collection framework, you can write this:

shapes.foreach(s -> s.setColor(RED));

The first way we call an outer iteration, For-each calls shapes the iterator() elements in the collection in turn. There are some problems with this external iteration:

    • The For loop is serial and must be done sequentially in the order of the elements in the collection;
    • The collection framework cannot optimize the control flow, such as sorting, parallelism, short-circuit evaluation, and lazy evaluation to improve performance.

      The above two questions we will be in the later article to gradually answer.

The second way we call the internal iteration, although the two pieces of code seems to be only grammatical differences, but in fact their internal differences are actually very large. The user returns control of the operation to the class library, allowing the class library to perform a variety of optimizations (such as disorderly execution, lazy evaluation, parallelism, and so on). In general, internal iterations make possible optimizations that are not possible in an external iteration.

The external iteration assumes what to do (set the shape to red) and how to do it (get the iterator instance and then loop through it), and the inner iteration is only responsible for what it does, leaving it to the class library. The code becomes clearer, and the collection class library can perform various optimizations internally.

1. What is Stream

Stream is not a collection element, it is not a data structure, it cannot hold data, it is more like a higher level Interator . Stream provides powerful data collection manipulation capabilities and is deeply integrated into existing collection classes and other JDK types. The operation of the stream can be combined into a pipeline (Pipeline). In the previous example, if I only wanted to change the blue color to red:

shapes.stream()      .filter(s -> s.getColor() == BLUE)      .forEach(s -> s.setColor(RED));

When you Collection raise a stream that generates the collection element, the stream() next filter() action produces a stream that contains only the blue shape, and finally, the blue shape is forEach set to red.

If we want to extract the blue shape into the new list, we can:

List<Shape> blue = shapes.stream()                          .filter(s -> s.getColor() == BLUE)                          .collect(Collectors.toList());

collect()The operation aggregates the elements it receives (this is the list), and collect() the parameters of the method are used to specify how the aggregation is done. Here we use toList() to export the element to the list.

If each shape is saved in Box , then we want to know which box contains at least one blue shape, which we can write:

Set<Box> hasBlueShape = shapes.stream()                               .filter(s -> s.getColor() == BLUE)                              .map(s -> s.getContainingBox())                              .collect(Collectors.toSet());

map()The operation passes through the mapping function (where the mapping function receives a shape and then returns the box containing it), converting the elements inside the input stream, and then generating a new stream.

If we need to get the total weight of the blue object, we can say this:

int sum = shapes.stream()                .filter(s -> s.getColor() == BLUE)                .mapToInt(s -> s.getWeight())                .sum();
2.Stream vs Collection

Flow (stream) and collection (Collection) Differences:

    • Collection is mainly used to manage and access elements;
    • Stream does not support direct manipulation and direct access to its elements, but only supports the result of operations on top of it through declarative operations;
    • Stream does not store values
    • The operation of the stream produces a result, but the stream does not change the data source;
    • Most of the stream's operations (Filter,map,sort, etc.) are implemented in an inert manner. This allows us to use a single traversal to complete the entire pipelined operation and to provide a more efficient implementation with short-circuit operations.
3. Lazy Evaluation vs Acute evaluation

filter()And map() Such an operation can be acute evaluation ( filter() for example, the acute evaluation needs to complete the filtering of all elements before the method returns), can also be lazy evaluation (by Stream means of filtering results, when and only when needed to filter operations) in the actual lazy operation can bring many benefits. For example, if we do lazy filtering, we can mix the filtering and other operations in the pipeline so that we do not need to traverse the data more than once. Similarly, if we search for the first element in a large collection that satisfies a certain condition, we can stop it immediately after we find it, rather than continue with the entire collection. (This is important for the infinite data source, the lazy evaluation of the limited data source is the optimization, but for the infinite data source is the decision, there is no lazy evaluation, the operation of the infinite data source will not be terminated)

For filter() map() Such operations, it is natural to think of it as a lazy evaluation operation, but whether or not they are really inert depends on their specific implementation. In addition, sum() operations such as generating values like this and forEach() the actions that produce side effects are naturally acute , because they have to produce concrete results.

Let's take the following code example:

int sum = shapes.stream()                .filter(s -> s.getColor() == BLUE)                .mapToInt(s -> s.getWeight())                .sum();

The filter() and map() are inert, which means that sum() no elements are extracted from the data source until the call is called. sum()after the operation, it will be put filter() , map() and sum() placed in the data source one traversal. This can significantly reduce the overhead of maintaining intermediate results.

4. Give me a chestnut??

The previous lengthy introduction concept is really boring, in order to facilitate understanding we use the Streams API to achieve a specific business scenario.

Suppose we have a property library project, which has a series of community, each cell has a list of cell names and listings, each house has a price, area and other properties. Now we need to filter out the community containing more than 100 square meters of housing, and sorted by cell name.

Let's take a look at how to do this without the streams API:

new ArrayList<>();for (Community community : communities) {        for (House house : community.houses) {            if (house.area > 100) { result.add(community); break; } } } Collections.sort(result, new Comparator<Community>() { @Override public int compare(Community c1, Community c2) { return c1.name.compareTo(c2.name); } }); return result;

If you use the streams API:

return communities.stream()          .filter(c -> c.houses.stream().anyMatch(h -> h.area>100))          .sorted(Comparator.comparing(c -> c.name))          .collect(Collectors.toList());

Zhang Lei Baron
Links: Https://juejin.im/post/57dc8edd0bd1d00057e804a6

Java8 new Features Chapter 3rd (Stream API)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.