Stream Data Stream in Java 8 and java8Stream data Stream

Source: Internet
Author: User

Stream Data Stream in Java 8 and java8Stream data Stream
Filter repeated Elements

The Stream interface supports the distinct method, which returns a Stream of elements (implemented based on the hashCode and equals methods of the elements generated by the Stream.

For example, the following code filters out all the even numbers in the list and ensures that there are no duplicates.

List <Dish> dishes = Dish. menu. stream (). filter (Dish: isVegetarian). collect (Collectors. toList (); skip the specified number of elements

Stream supports the skip (n) method and returns a Stream that discards the first n elements. If there are less than n elements in the stream, an empty stream is returned. Limit (n) and skip (n) are complementary.

List <Dish> dishSkip = Dish. menu. stream (). filter (d-> d. getCalories ()> 300 ). skip (2) // removes the first two elements from the compliant set and returns the result. collect (Collectors. toList (); dishSkip. forEach (System. out: println); map operation

Stream supports the map method, which accepts a function as a parameter. This function will be applied to each element and be reflected into a new element.

List <String> list = st. skip (0 ). limit (2 ). map (s-> s. toUpperCase ()). collect (Collectors. toList (); element summation List <Integer> numbers = Arrays. asList (3, 4, 5, 1, 2); int sum1 = numbers. stream (). reduce (0, (a, B)-> a + B); System. out. println (sum1); int sum2 = numbers. stream (). reduce (0, Integer: sum); System. out. println (sum2); maximum value int max = numbers. stream (). reduce (0, Integer: max); System. out. println (max); Minimum value // reduce does not accept the initial value, returns an Optional object (considering that the stream does not have any elements) Optional <Integer> min = numbers. stream (). reduce (Integer: min); min. ifPresent (System. out: println );

Related Article

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.