首页 > 编程语言 >Stream In Java

Stream In Java

时间:2022-11-27 02:56:15浏览次数:55  
标签:Java Stream stream List number collect method

https://www.geeksforgeeks.org/stream-in-java/

 

Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.
The features of Java stream are –

  • A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
  • Streams don’t change the original data structure, they only provide the result as per the pipelined methods.
  • Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result.

Different Operations On Streams-
Intermediate Operations:

 
  1. map: The map method is used to returns a stream consisting of the results of applying the given function to the elements of this stream.
    List number = Arrays.asList(2,3,4,5);
    List square = number.stream().map(x->x*x).collect(Collectors.toList());
  2. filter: The filter method is used to select elements as per the Predicate passed as argument.
    List names = Arrays.asList("Reflection","Collection","Stream");
    List result = names.stream().filter(s->s.startsWith("S")).collect(Collectors.toList());
  3. sorted: The sorted method is used to sort the stream.
    List names = Arrays.asList("Reflection","Collection","Stream");
    List result = names.stream().sorted().collect(Collectors.toList());

Terminal Operations:

  1. collect: The collect method is used to return the result of the intermediate operations performed on the stream.
    List number = Arrays.asList(2,3,4,5,3);
    Set square = number.stream().map(x->x*x).collect(Collectors.toSet());
  2. forEach: The forEach method is used to iterate through every element of the stream.
    List number = Arrays.asList(2,3,4,5);
    number.stream().map(x->x*x).forEach(y->System.out.println(y));
  3. reduce: The reduce method is used to reduce the elements of a stream to a single value.
    The reduce method takes a BinaryOperator as a parameter.   <iframe data-google-container-id="2" data-is-safeframe="true" data-load-complete="true" frameborder="0" height="280" id="google_ads_iframe_/27823234/GFG_Desktop_PostContent_336x280_0" marginheight="0" marginwidth="0" scrolling="no" src="https://88412e4301913956b28fbd58060d7148.safeframe.googlesyndication.com/safeframe/1-0-40/html/container.html" title="3rd party ad content" width="336"></iframe>

    List number = Arrays.asList(2,3,4,5);
    int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);

    Here ans variable is assigned 0 as the initial value and i is added to it .

Program to demonstrate the use of Stream

 
//a simple program to demonstrate the use of stream in java import java.util.*; import java.util.stream.*;    class Demo {   public static void main(String args[])   {        // create a list of integers     List<Integer> number = Arrays.asList(2,3,4,5);        // demonstration of map method     List<Integer> square = number.stream().map(x -> x*x).                            collect(Collectors.toList());     System.out.println(square);        // create a list of String     List<String> names =                 Arrays.asList("Reflection","Collection","Stream");        // demonstration of filter method     List<String> result = names.stream().filter(s->s.startsWith("S")).                           collect(Collectors.toList());     System.out.println(result);        // demonstration of sorted method     List<String> show =             names.stream().sorted().collect(Collectors.toList());     System.out.println(show);        // create a list of integers     List<Integer> numbers = Arrays.asList(2,3,4,5,2);        // collect method returns a set     Set<Integer> squareSet =          numbers.stream().map(x->x*x).collect(Collectors.toSet());     System.out.println(squareSet);        // demonstration of forEach method     number.stream().map(x->x*x).forEach(y->System.out.println(y));        // demonstration of reduce method     int even =        number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);        System.out.println(even);   } }

Output:

[4, 9, 16, 25]
[Stream]
[Collection, Reflection, Stream]
[16, 4, 9, 25]
4
9
16
25
6

Important Points/Observations:

  1. A stream consists of source followed by zero or more intermediate methods combined together (pipelined) and a terminal method to process the objects obtained from the source as per the methods described.
  2. Stream is used to compute elements as per the pipelined methods without altering the original value of the object.

This article is contributed by Akash Ojha .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

标签:Java,Stream,stream,List,number,collect,method
From: https://www.cnblogs.com/kungfupanda/p/16928898.html

相关文章

  • Comparable vs Comparator in Java
    https://www.geeksforgeeks.org/comparable-vs-comparator-in-java/ Javaprovidestwointerfacestosortobjectsusingdatamembersoftheclass:  Comparabl......
  • equals() and hashCode() methods in Java
    https://www.geeksforgeeks.org/equals-hashcode-methods-java/ Java.lang.objecthastwoveryimportantmethodsdefined:publicbooleanequals(Objectobj)andp......
  • enum in Java
    https://www.geeksforgeeks.org/enum-in-java/Enumerationsservethepurposeofrepresentingagroupofnamedconstantsinaprogramminglanguage.Forexample,t......
  • Generics in Java
    https://www.geeksforgeeks.org/generics-in-java/ Generics means parameterizedtypes.Theideaistoallowtype(Integer,String,…etc.,anduser-defined......
  • java发送邮件
    一邮件协议收发邮件具有与HTTP协议相同的邮件传输协议.SMTP:(SimpleMailTransferProtocol,简单邮件传输协议)发邮件协议POP3:(PostOfficeProtocolVersion3,邮局协议第......
  • Java中YYYY-MM-dd在跨年时出现的bug
    先看一张图:Bug的产生原因:日期格式化时候,把yyyy-MM-dd写成了YYYY-MM-dd Bug分析:当时间是2019-08-31时,publicclassDateTest{publicstaticvoidmain(Strin......
  • java中乐观锁CAS的实现探究——AtomicInteger
    CASCAS——compareandswap,比较并交换。是一种乐观锁的实现方式。更新操作时,在每次更新之前,都先比较一下被更新的目标T,值是不是等于读取到的旧值O,如果相等,则认为在读取......
  • JAVA网络编程TCP实现聊天功能,附在IDEA中同时运行2个或以上相同的java程序
    在IDEA中同时运行2个或以上相同的java程序在日常编写测试代码时,有时候会需要在idea上同时运行两个及以上相同的java程序,如:想运行两个CLIENTLOGIN测试聊天室效果。1.点击E......
  • java9
    Java9新特性Java9发布于2017年9月22日,带来了很多新特性,其中最主要的变化是已经实现的模块化系统。接下来我们会详细介绍Java9的新特性。Java9新特性模块系......
  • 基于java+swing的图书管理系统
    功能展示登录管理员-主界面管理员-增加书籍管理员-更新和删除书籍管理员-查找书籍管理员-查找所有书籍管理员-添加用户管理员-更新和删除用户管理员-查找......