java8-Introduction Stream (1)

Source: Internet
Author: User
Tags stream api

Collections are the most used APIs in Java. What can you do without a set? Almost every Java application manufactures processing collections. Collections are very basic to many programming tasks: they allow you to group and process data. To explain how the collection works, imagine that you are preparing a series of dishes, forming a menu, and then traversing again, adding up the heat of each dish. You may want to choose a dish that is lower in calories to form a healthy special menu. Although collections are essential for almost any Java application, the lack of collection operations is far from perfect.

A.Many of the task logic involves database-like operations, such as classifying several dishes by category (such as vegan dishes), or finding the most expensive dish. How many times have you re-implemented these operations yourself with iterators? Most databases allow you to specify these actions declaratively. For example, the following SQL query statement can be used to select the lower calorie dish name: Select name from dishes where calorie < 400. You see, you don't need to implement how to filter based on the attributes of your dishes (such as using iterators and accumulators), you just need to express what you want. This basic idea means that you don't have to worry about how to implement these query statements in a display.

B. What if you are dealing with a large number of elements? To provide performance, you need to work in parallel and take advantage of multi-core architectures. But writing parallel code is more complicated than using iterators, and debugging is hard enough!

What can the designer of the Java language do to help save valuable time and make it easier for your programmer to live? As you may have guessed, the answer is flow .

1. What is a stream

A stream is a new member of the Java API that allows you to handle a collection of data declaratively (expressed by a query statement, rather than by writing an implementation on a temporary basis). For now, you can think of them as advanced iterators that traverse Datasets. In addition, streams can be processed transparently in parallel, and you don't have to write any multithreaded code! Let's take a quick look at the benefits of using streams. The code below both returns the name of the low-calorie dish, and is sorted by calories, one using Java7, the other written, and the other with the Java8 stream. Compare it. Don't worry about how the JAVA8 code is written:

Before (JAVA7):

1List<dish> lowcaloricdishes =NewArraylist<>();2list<dish> menu = Arrays.aslist (NewDish ("1", 100),NewDish ("1", 300),NewDish ("1", 500),3                 NewDish ("1", 1000));4          for(Dish D:menu) {//using iterators to filter elements5             if(D.getcalories () < 400){ 6 Lowcaloricdishes.add (d);7             }8         }9Collections.sort (Lowcaloricdishes,NewComparator<dish> () {//sorting with anonymous dishesTen  One @Override A              Public intCompare (Dish O1, Dish O2) { -                 returnInteger.compare (O1.getcalories (), o2.getcalories ()); -             } the         }); -List<string> Lowcaloricdishesname =NewArraylist<>(); -          for(Dish d:lowcaloricdishes) { -Lowcaloricdishesname.add (D.getname ());//list of processed dishes after sorting +}

In this code, you use a "garbage variable" lowcaloricdishes. Its only function is as a disposable intermediate container. In Java8, the implementation details are placed in the library where it should belong.

1List<string> Lowcaloricdishesname =NewArraylist<>();2Lowcaloricdishesname =3 Menu.stream ()4. Filter (D-d.getcalories () < 400)//choose from 400 calories or less5. Sorted (Comparator.comparing (dish::getcalories))//Sort by calories6. Map (Dish::getname)//name of the dish to be extracted7. Collect (Collectors.tolist ());//Save all the names in the list

In order to execute this code in parallel using a multicore architecture, you only need to change the stream () to Parallelstream ();

 1  lowcaloricdishesname = 2    Menu.parallelstream ()   3  . Filter (D-d.getcalories () <) //   Choose 400-calorie dishes  4 . Sorted (comparator.comparing (dish::getcalories)) //  Sort by calories  5 . Map (dish::getname) //  Extract the name of the dish  6 . Collect (Collectors.tolist ()); //  

You might think about what happened when the Parallelstream method was called. How many threads are used? How much is the performance improvement? These questions will be discussed in detail in the future. Now, you see, from a software engineer's point of view, there are several obvious benefits to the new approach.

A.the code is written in a declarative way: It shows what you want to accomplish (filter low-calorie dishes) instead of how to implement an operation (using control-flow statements such as loops and if conditions). As you've seen before, this approach coupled with behavioral parameterization allows you to easily respond to changing needs: You can easily create a code version that uses Lamba expressions to filter high-calorie dishes instead of copying and pasting code.

B . You can link several basic action filters to express complex data processing lines (sorted, map, and collect operations, as shown in the following filter), while keeping the code clear and readable. The result of the filter is passed to the sorted method, then to the map method, and finally to the Collect method.

Because the operations such as filter, sorted, map, and collect are high-level artifacts unrelated to the specific threading model, their internal implementations can be single-threaded or transparent enough to take advantage of your multilevel architecture! In practice, this means that you don't have to worry about threads and locks in order to make certain data processing tasks parallel, and the Stream API is ready for you!

2. Introduction to Streaming

To discuss the flow, let's talk about the collection first, which is the easiest way to get started. The collection in JAVA8 supports a new stream method, which returns a stream (the interface is defined in Java.util.stream.Stream). As you'll see later, there are a number of ways you can get a stream, such as a stream element that leverages a range of values or is generated from an I/O resource.

So what exactly is the flow? The short definition is "sequence of elements generated from sources that support data processing operations." Let's step through the definition.

A. Sequence of elements -like a collection, a stream also provides an interface to access a set of ordered values for a particular element type. Because the collection is a data structure, its main purpose is to store and visit a specific time/space complexity

Elements (ArrayList and LinkedList). But the purpose of the flow is to express calculations, such as simple filter, sorted, and map in front of you. The set is about the data, the flow is the calculation. We explain the idea in detail in the following sections.

B. Source -The stream uses a source that provides data, such as a collection, an array, or an input/output resource. Note that the original order is preserved when the stream is generated from an ordered collection. The stream generated by the list, whose elements are in the same order as the list.

c. Data processing operations -The stream's data processing capabilities support database-like operations, as well as common operations in functional programming languages such as filter, map, reduce, find, match, sort, and so on. Flow operations can be executed sequentially or in parallel.

In addition, there are two important characteristics of flow operations.

A. pipelining -Many of the flow operations themselves return a stream, so that multiple operations can be linked together to form a large, large pipeline. This makes some of our later optimizations possible, such as delays and short circuits. Pipeline operation can be considered as a database query to the data source.

B. Internal iterations -unlike collections that use iterators to display iterations, the iterative operation of a stream is behind the scenes.

Let's take a look at the code that embodies all these concepts:

Definition of the dish class:

1  Packagecom.example.demo13;2 3  Public classDish {4     Private FinalString name;5     Private Final Booleanvegetarion;6     Private Final intcalories;7     Private Finaltype type;8      Public enumtype{9 meat, FISH, otherTen     } One      PublicDish (String name,BooleanVegetarion,intcalories, type type) { A          This. Name =name; -          This. vegetarion =vegetarion; -          This. Calories =calories; the          This. Type =type; -     } -      PublicString GetName () { -         returnname; +     } -      Public Booleanisvegetarion () { +         returnvegetarion; A     } at      Public intgetcalories () { -         returncalories; -     } -      PublicType GetType () { -         returntype; -     } in      -}

The definition of the class where the Main method resides:

1  Packagecom.example.demo13;2 3 Importjava.util.Arrays;4 Importjava.util.List;5 Importjava.util.stream.Collectors;6 7  Public classDemo13 {8      Public Static voidMain (string[] args) {9list<dish> menu =Arrays.aslist (Ten                 NewDish ("Pork",false, 800, Dish.Type.MEAT), One                 NewDish ("Beef",false, 700, Dish.Type.MEAT), A                 NewDish ("Chicken",false, 400, Dish.Type.MEAT), -                 NewDish ("French fries",true, 530, Dish.Type.OTHER), -                 NewDish ("Rice",true, 350, Dish.Type.OTHER), the                 NewDish ("Season fruit",true, 120, Dish.Type.OTHER), -                 NewDish ("Pizza",true, 550, Dish.Type.OTHER), -                 NewDish ("Prawns",false, 300, Dish.Type.FISH), -                 NewDish ("Salmon",false, 450, Dish.Type.FISH)); +List<string> Treenhighcaloricdishnames = -Menu.stream ().//get stream from menu (list of dishes) +Filter (D-d.getcalories () > 300).//set up a pipeline operation: first select high-calorie dishes AMap (dish::getname).//get the name of the dish atLimit (3).//Select only the first three -Collect (Collectors.tolist ());//results are saved in another list collection - System.out.println (treenhighcaloricdishnames); -     } -}

java8-Introduction Stream (1)

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.