Java 8 Stream – Java Stream

Filed Under: Java

Welcome to Java 8 Stream API tutorial. In the last few java 8 posts, we looked into Java 8 Interface Changes and Functional Interfaces and Lambda Expressions. Today we will look into one of the major API introduced in Java 8 – Java Stream.

Java 8 Stream

java 8 stream, java stream, java streams, java 8 streams

  1. Java 8 Stream
  2. Collections and Java Stream
  3. Functional Interfaces in Java 8 Stream
    1. Function and BiFunction
    2. Predicate and BiPredicate
    3. Consumer and BiConsumer
    4. Supplier
  4. java.util.Optional
  5. java.util.Spliterator
  6. Java Stream Intermediate and Terminal Operations
  7. Java Stream Short Circuiting Operations
  8. Java Stream Examples
    1. Creating Java Streams
    2. Converting Java Stream to Collection or Array
    3. Java Stream Intermediate Operations
    4. Java Stream Terminal Operations
  9. Java 8 Stream API Limitations

Java Stream

Before we look into Java Stream API Examples, let’s see why it was required. Suppose we want to iterate over a list of integers and find out sum of all the integers greater than 10.

Prior to Java 8, the approach to do it would be:

private static int sumIterator(List<Integer> list) {
	Iterator<Integer> it = list.iterator();
	int sum = 0;
	while (it.hasNext()) {
		int num =;
		if (num > 10) {
			sum += num;
	return sum;

There are three major problems with the above approach:

  1. We just want to know the sum of integers but we would also have to provide how the iteration will take place, this is also called external iteration because client program is handling the algorithm to iterate over the list.
  2. The program is sequential in nature, there is no way we can do this in parallel easily.
  3. There is a lot of code to do even a simple task.

To overcome all the above shortcomings, Java 8 Stream API was introduced. We can use Java Stream API to implement internal iteration, that is better because java framework is in control of the iteration.

Internal iteration provides several features such as sequential and parallel execution, filtering based on the given criteria, mapping etc.

Most of the Java 8 Stream API method arguments are functional interfaces, so lambda expressions work very well with them. Let’s see how can we write above logic in a single line statement using Java Streams.

private static int sumStream(List<Integer> list) {
	return -> i > 10).mapToInt(i -> i).sum();

Notice that above program utilizes java framework iteration strategy, filtering and mapping methods and would increase efficiency.

First of all we will look into the core concepts of Java 8 Stream API and then we will go through some examples for understanding most commonly used methods.

Collections and Java Stream

A collection is an in-memory data structure to hold values and before we start using collection, all the values should have been populated. Whereas a java Stream is a data structure that is computed on-demand.

Java Stream doesn’t store data, it operates on the source data structure (collection and array) and produce pipelined data that we can use and perform specific operations. Such as we can create a stream from the list and filter it based on a condition.

Java Stream operations use functional interfaces, that makes it a very good fit for functional programming using lambda expression. As you can see in the above example that using lambda expressions make our code readable and short.

Java 8 Stream internal iteration principle helps in achieving lazy-seeking in some of the stream operations. For example filtering, mapping, or duplicate removal can be implemented lazily, allowing higher performance and scope for optimization.

Java Streams are consumable, so there is no way to create a reference to stream for future usage. Since the data is on-demand, it’s not possible to reuse the same stream multiple times.

Java 8 Stream support sequential as well as parallel processing, parallel processing can be very helpful in achieving high performance for large collections.

All the Java Stream API interfaces and classes are in the package. Since we can use primitive data types such as int, long in the collections using auto-boxing and these operations could take a lot of time, there are specific classes for primitive types – IntStream, LongStream and DoubleStream.

Functional Interfaces in Java 8 Stream

Some of the commonly used functional interfaces in the Java 8 Stream API methods are:

  1. Function and BiFunction: Function represents a function that takes one type of argument and returns another type of argument. Function<T, R> is the generic form where T is the type of the input to the function and R is the type of the result of the function.

    For handling primitive types, there are specific Function interfaces – ToIntFunction, ToLongFunction, ToDoubleFunction, ToIntBiFunction, ToLongBiFunction, ToDoubleBiFunction, LongToIntFunction, LongToDoubleFunction, IntToLongFunction, IntToDoubleFunction etc.

    Some of the Stream methods where Function or it’s primitive specialization is used are:

    • <R> Stream<R> map(Function<? super T, ? extends R> mapper)
    • IntStream mapToInt(ToIntFunction<? super T> mapper) – similarly for long and double returning primitive specific stream.
    • IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper) – similarly for long and double
    • <A> A[] toArray(IntFunction<A[]> generator)
    • <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner)
  2. Predicate and BiPredicate: It represents a predicate against which elements of the stream are tested. This is used to filter elements from the java stream. Just like Function, there are primitive specific interfaces for int, long and double.

    Some of the Stream methods where Predicate or BiPredicate specializations are used are:

    • Stream<T> filter(Predicate<? super T> predicate)
    • boolean anyMatch(Predicate<? super T> predicate)
    • boolean allMatch(Predicate<? super T> predicate)
    • boolean noneMatch(Predicate<? super T> predicate)
  3. Consumer and BiConsumer: It represents an operation that accepts a single input argument and returns no result. It can be used to perform some action on all the elements of the java stream.

    Some of the Java 8 Stream methods where Consumer, BiConsumer or it’s primitive specialization interfaces are used are:

    • Stream<T> peek(Consumer<? super T> action)
    • void forEach(Consumer<? super T> action)
    • void forEachOrdered(Consumer<? super T> action)
  4. Supplier: Supplier represent an operation through which we can generate new values in the stream. Some of the methods in Stream that takes Supplier argument are:
    • public static<T> Stream<T> generate(Supplier<T> s)
    • <R> R collect(Supplier<R> supplier,BiConsumer<R, ? super T> accumulator,BiConsumer<R, R> combiner)


Java Optional is a container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value. Stream terminal operations return Optional object. Some of these methods are:

  • Optional<T> reduce(BinaryOperator<T> accumulator)
  • Optional<T> min(Comparator<? super T> comparator)
  • Optional<T> max(Comparator<? super T> comparator)
  • Optional<T> findFirst()
  • Optional<T> findAny()


For supporting parallel execution in Java 8 Stream API, Spliterator interface is used. Spliterator trySplit method returns a new Spliterator that manages a subset of the elements of the original Spliterator.

Java Stream Intermediate and Terminal Operations

Java Stream API operations that returns a new Stream are called intermediate operations. Most of the times, these operations are lazy in nature, so they start producing new stream elements and send it to the next operation. Intermediate operations are never the final result producing operations. Commonly used intermediate operations are filter and map.

Java 8 Stream API operations that returns a result or produce a side effect. Once the terminal method is called on a stream, it consumes the stream and after that we can’t use stream. Terminal operations are eager in nature i.e they process all the elements in the stream before returning the result. Commonly used terminal methods are forEach, toArray, min, max, findFirst, anyMatch, allMatch etc. You can identify terminal methods from the return type, they will never return a Stream.

Java Stream Short Circuiting Operations

An intermediate operation is called short circuiting, if it may produce finite stream for an infinite stream. For example limit() and skip() are two short circuiting intermediate operations.

A terminal operation is called short circuiting, if it may terminate in finite time for infinite stream. For example anyMatch, allMatch, noneMatch, findFirst and findAny are short circuiting terminal operations.

Java Stream Examples

I have covered almost all the important parts of the Java 8 Stream API. It’s exciting to use this new API features and let’s see it in action with some java stream examples.

Creating Java Streams

There are several ways through which we can create a java stream from array and collections. Let’s look into these with simple examples.

  1. We can use Stream.of() to create a stream from similar type of data. For example, we can create Java Stream of integers from a group of int or Integer objects.
    Stream<Integer> stream = Stream.of(1,2,3,4);
  2. We can use Stream.of() with an array of Objects to return the stream. Note that it doesn’t support autoboxing, so we can’t pass primitive type array.
    Stream<Integer> stream = Stream.of(new Integer[]{1,2,3,4}); 
    //works fine
    Stream<Integer> stream1 = Stream.of(new int[]{1,2,3,4}); 
    //Compile time error, Type mismatch: cannot convert from Stream<int[]> to Stream<Integer>
  3. We can use Collection stream() to create sequential stream and parallelStream() to create parallel stream.
    List<Integer> myList = new ArrayList<>();
    for(int i=0; i<100; i++) myList.add(i);
    //sequential stream
    Stream<Integer> sequentialStream =;
    //parallel stream
    Stream<Integer> parallelStream = myList.parallelStream();
  4. We can use Stream.generate() and Stream.iterate() methods to create Stream.
    Stream<String> stream1 = Stream.generate(() -> {return "abc";});
    Stream<String> stream2 = Stream.iterate("abc", (i) -> i);
  5. Using and String.chars() methods.
    LongStream is = long[]{1,2,3,4});
    IntStream is2 = "abc".chars();

Converting Java Stream to Collection or Array

There are several ways through which we can get a Collection or Array from a java Stream.

  1. We can use java Stream collect() method to get List, Map or Set from stream.
    Stream<Integer> intStream = Stream.of(1,2,3,4);
    List<Integer> intList = intStream.collect(Collectors.toList());
    System.out.println(intList); //prints [1, 2, 3, 4]
    intStream = Stream.of(1,2,3,4); //stream is closed, so we need to create it again
    Map<Integer,Integer> intMap = intStream.collect(Collectors.toMap(i -> i, i -> i+10));
    System.out.println(intMap); //prints {1=11, 2=12, 3=13, 4=14}
  2. We can use stream toArray() method to create an array from the stream.
    Stream<Integer> intStream = Stream.of(1,2,3,4);
    Integer[] intArray = intStream.toArray(Integer[]::new);
    System.out.println(Arrays.toString(intArray)); //prints [1, 2, 3, 4]

Java Stream Intermediate Operations

Let’s look into commonly used java Stream intermediate operations example.

  1. Stream filter() example: We can use filter() method to test stream elements for a condition and generate filtered list.
    List<Integer> myList = new ArrayList<>();
    for(int i=0; i<100; i++) myList.add(i);
    Stream<Integer> sequentialStream =;
    Stream<Integer> highNums = sequentialStream.filter(p -> p > 90); //filter numbers greater than 90
    System.out.print("High Nums greater than 90=");
    highNums.forEach(p -> System.out.print(p+" "));
    //prints "High Nums greater than 90=91 92 93 94 95 96 97 98 99 "
  2. Stream map() example: We can use map() to apply functions to an stream. Let’s see how we can use it to apply upper case function to a list of Strings.
    Stream<String> names = Stream.of("aBc", "d", "ef");
    System.out.println( -> {
    		return s.toUpperCase();
    //prints [ABC, D, EF]
  3. Stream sorted() example: We can use sorted() to sort the stream elements by passing Comparator argument.
    Stream<String> names2 = Stream.of("aBc", "d", "ef", "123456");
    List<String> reverseSorted = names2.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
    System.out.println(reverseSorted); // [ef, d, aBc, 123456]
    Stream<String> names3 = Stream.of("aBc", "d", "ef", "123456");
    List<String> naturalSorted = names3.sorted().collect(Collectors.toList());
    System.out.println(naturalSorted); //[123456, aBc, d, ef]
  4. Stream flatMap() example: We can use flatMap() to create a stream from the stream of list. Let’s see a simple example to clear this doubt.
    Stream<List<String>> namesOriginalList = Stream.of(
    	Arrays.asList("David", "Lisa"),
    //flat the stream from List<String> to String stream
    Stream<String> flatStream = namesOriginalList
    	.flatMap(strList ->;

Java Stream Terminal Operations

Let’s look at some of the java stream terminal operations example.

  1. Stream reduce() example: We can use reduce() to perform a reduction on the elements of the stream, using an associative accumulation function, and return an Optional. Let’s see how we can use it multiply the integers in a stream.
    Stream<Integer> numbers = Stream.of(1,2,3,4,5);
    Optional<Integer> intOptional = numbers.reduce((i,j) -> {return i*j;});
    if(intOptional.isPresent()) System.out.println("Multiplication = "+intOptional.get()); //120
  2. Stream count() example: We can use this terminal operation to count the number of items in the stream.
    Stream<Integer> numbers1 = Stream.of(1,2,3,4,5);
    System.out.println("Number of elements in stream="+numbers1.count()); //5
  3. Stream forEach() example: This can be used for iterating over the stream. We can use this in place of iterator. Let’s see how to use it for printing all the elements of the stream.
    Stream<Integer> numbers2 = Stream.of(1,2,3,4,5);
    numbers2.forEach(i -> System.out.print(i+",")); //1,2,3,4,5,
  4. Stream match() examples: Let’s see some of the examples for matching methods in Stream API.
    Stream<Integer> numbers3 = Stream.of(1,2,3,4,5);
    System.out.println("Stream contains 4? "+numbers3.anyMatch(i -> i==4));
    //Stream contains 4? true
    Stream<Integer> numbers4 = Stream.of(1,2,3,4,5);
    System.out.println("Stream contains all elements less than 10? "+numbers4.allMatch(i -> i<10));
    //Stream contains all elements less than 10? true
    Stream<Integer> numbers5 = Stream.of(1,2,3,4,5);
    System.out.println("Stream doesn't contain 10? "+numbers5.noneMatch(i -> i==10));
    //Stream doesn't contain 10? true
  5. Stream findFirst() example: This is a short circuiting terminal operation, let’s see how we can use it to find the first string from a stream starting with D.
    Stream<String> names4 = Stream.of("Pankaj","Amit","David", "Lisa");
    Optional<String> firstNameWithD = names4.filter(i -> i.startsWith("D")).findFirst();
    	System.out.println("First Name starting with D="+firstNameWithD.get()); //David

Java 8 Stream API Limitations

Java 8 Stream API brings a lot of new stuffs to work with list and arrays, but it has some limitations too.

  1. Stateless lambda expressions: If you are using parallel stream and lambda expressions are stateful, it can result in random responses. Let’s see it with a simple program.

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    public class StatefulParallelStream {
    	public static void main(String[] args) {
    		List<Integer> ss = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
    		List<Integer> result = new ArrayList<Integer>();
    		Stream<Integer> stream = ss.parallelStream();
     -> {
    		        synchronized (result) {
    		          if (result.size() < 10) {
    				return s;
    		    }).forEach( e -> {});

    If we run above program, you will get different results because it depends on the way stream is getting iterated and we don’t have any order defined for parallel processing. If we use sequential stream, then this problem will not arise.

  2. Once a Stream is consumed, it can’t be used later on. As you can see in above examples that every time I am creating a stream.
  3. There are a lot of methods in Stream API and the most confusing part is the overloaded methods. It makes the learning curve time taking.

That’s all for Java 8 Stream example tutorial. I am looking forward to use this feature and make the code readable with better performance through parallel processing.

Reference: Java Stream API Doc [no_toc]


  1. Jeevak Gajbhiye says:

    Excellent Post. Thanks

    1. Hamraj says:

      Jeevak Interviewchi tayari karat aahes ka??

  2. Sreejith says:

    Still I refer to this page even 6 years after it got published. Thanks for the good job.

  3. Sandeep says:

    very nice information on streams… thanks

  4. Gopu Ravi says:

    HI Pankaj,
    Nice Article and well covered the concept of stream

  5. Arnab Dutta says:

    Say I have :
    Class1{ {Stud_ID10,Marks100} , {Stud_ID20,Marks200} , {Stud_ID30,Marks300} … } ,
    Class2{ ….similar to above…} ,

    Class20{ ….similar to above…}
    } ,
    Class1{ ….similar to above…}
    …similar to above…

    Class50{…similar to above…}
    } ,

    Class1{ ….similar to above…}
    …similar to above…

    Class90 {…similar to above…}

    Assuming College2 is AlphaNum,
    Class90 is AlphaNum,
    Stud_ID10 is AlphaNum,
    Marks100 is number

    How to get the average of all student marks under University having College 1…N ?

  6. sudarshan says:

    Very helpful to understand stream.

    1. aa says:

      Very helpful information.

  7. Yoseph A Hailu says:

    It is a very good write about stream. I am new to Java 8 but you presented it so well that i understood it quickly.
    Thanks once again for the write.

  8. Anonymous says:

    NIce tutorials. Facing an issue these days, program images are not visible only the theory protion is visible.

    1. Pankaj says:

      Sorry about that, I was trying lazy load images but it was causing some issues. I have removed that and images should load perfectly fine now.

  9. Akila says:

    Hello sir.. am having doubt in iteration and merging.
    Say ,I am given with some users . And I want to iterate group to check if the user exist in any of the groups . and if the user exist in more than one group ,get their module ,function and action details which are stored in groups database. Can you code the solution in java?

  10. Anwar Reefat says:

    I learned a lot from your articles.
    Thanks a lot.

  11. Amrita says:

    Hi all,
    I want to apply streams to the following code. But unable to successfully fo it. Can anyone help me in this.

    File backupFile = null;
    boolean found = false;
    List files = Arrays.asList(info.getServiceName() + “.txt”,
    info.getServiceName() + “.json”,
    for (String file : files) {
    backupFile = (new File(backupFileLocation, file));
    if (backupFile.exists()) {
    found = true;

    if (found) {
    } else {
    //throws exception

  12. Yakub says:

    Good post

  13. Khushwinder says:


    I have a question. When i run the below program :

    long startTime1 = System.currentTimeMillis();
    long endTime1 = System.currentTimeMillis();
    long duration1 = (endTime1 – startTime1);
    System.out.println(“sumIterator “+duration1);

    long startTime = System.currentTimeMillis();
    long endTime = System.currentTimeMillis();
    long duration = (endTime – startTime);
    System.out.println(“sumStream “+duration);

    I am getting the below output:
    sumIterator 16
    sumStream 110
    Clearly, stream method is using more time. Why would you write that streams are more efficient?


  14. Mohammed Farooq says:

    Awesome explanation 🙂

  15. Shailesh says:

    Very helpful and nice.

  16. Latif says:

    what do you mean by
    Java Streams are consumable, so there is no way to create a reference to stream for future usage. Since the data is on-demand, it’s not possible to reuse the same stream multiple times.

    1. Latif says:

      Got it ,
      By looking at your Example
      Tq 🙂

    2. Juned Akhtar says:

      Stream concept is quite interesting. very easy to process data with pre-defined methods…amazing!!

  17. Devi says:

    add Generics Integer type in List it will solve

  18. Aakash says:

    What’s the role for the forEach(e->{}) function in the last code you have written? The one about parallel streams?

  19. Vinayak A says:

    Hi Sir,

    Thanks for sharing such a nice post.

  20. evrim says:

    In StatefulParallelStream, you get a parallel stream and then use synchronization on that parallel stream,so it kills any benefit of parallel stream and instead makes it less performant, Do you have any explanation why do you think that it makes sense?

  21. Manmohan Sharma says:

    Nice article, thanks Pankaj

  22. suraj says:

    Hi..I am new to Java 8 features and this may be a stupid question but I am stuck at this point.

    I am trying to run following code but it gives compile time error.

    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.List;
    import java.util.function.Predicate;
    import ch.lambdaj.Lambda;

    public class LambdajTest {

    public static void main(String[] args) {

    List list = new ArrayList();

    int sum = -> i > 10).mapToInt(i -> i).sum();


    Error is :- i cannot be resolved to a variable.

    Kindly provide solution.
    Thanks in advance.

    1. lohith says:

      hi bro,

      you are not declaring ‘i ‘ variable of any type..

      so that the compiler says ” ye man i’m not able to understand what type of variable is ‘I’ ”

      declare int i; at the top or after elements added…

      1. suraj says:

        hi bro thanks for reply…but it does not solve the problem…

        as per my knowledge, there is no need to declare the variable (I have tried it & it didn’t work out) because this is what Lambdaj’s syntax.( you can read ADITYA VALLURU’s comment and Pankaj’s reply on same page)

        1. gopal says:

          replace List list = new ArrayList(); with List list = new ArrayList();
          It will resolve problem

          1. dimitris says:

            You can declare list using Generics as:
            List&ltInteger&gt list = new ArrayList&lt&gt();

            you can cast Object type variable i to int in lambda expressions:
            int sum = -> (int)i >= 10).mapToInt(i -> (int)i).sum();

          2. gbdcool says:

            List<Integer> list = new ArrayList();

        2. AlekhyaBodla says:

          List list = new ArrayList();

          int sum = -> i > 10).mapToInt(i -> i).sum();

          Comment is not taking angular brackets. but you need put generics.
          Integer in the creation of List.

      2. Pierrot Mongonnam says:

        some how this site doesn’t accept some characters and I didn’t see the notice for the Reply Text Area. As I said in a previous post, I don’t know whether you could solve your problem if not, the problem is that you are declaring implicitly a list of something.To solve the problem please declare your list explicitly as list of Integers e.g. like this List = new ArrayList(); .

        1. Pankaj says:

          You need to wrap your code inside pre tags otherwise they will be eaten up by HTML because angular brackets will be treated as html elements.

          1. Devi says:

            public static void main(String[] args) {

            List list = new ArrayList();


            int sum = -> i>10).mapToInt(i -> i).sum();


            try this it will resolve ur issue.

          2. palani says:

            import java.util.ArrayList;
            import java.util.Arrays;
            import java.util.Collections;
            import java.util.List;
            import java.util.function.Consumer;

            public class A {

            public static void main(String[] args) {
            List list = Arrays.asList(10, 20, 30, 10, 20);
            int sum =
            .filter(i -> i > 1)
            .mapToInt(i -> i)


      3. Yathiraj says:

        Since you are using > operator inside filter method it expect you to define data type of array list.
        declare list as List list = new ArrayList();

    2. Richard says:

      your compiler version is 1.8?

    3. Pierrot Mongonnam says:

      Hi Broh,

      I was just surfing on the Net and checking for interesting tutorials about the new Java 8 Stream API, then I saw your problem. Hope you found the solution, if not here what is wrong with your code:

      the point is the Java 8 Stream API is making a strong use of generics and this is your Problem. By declaring your list like you did: List list = new ArrayList();
      you’ve declared implicitly your List as following List which means a list of objects. Thus you couldn’t filter your list like you did: filter(i -> i > 10). The compiler got confused because he doesn’t know how to compare an object with an Integer. So please declare your list like the following and it will work:

      List list = new ArrayList();

    4. Pierrot Mongonnam says:

      List list = new ArrayList() Declare it explicitly as list of Integer. This site doesn’t accept my Code as I want. Anyway what you should do is to declare your list explicitly as a List of Integer with the Diamond Operator

      1. gbdcool says:

        Like this right?
        List<Integer> list = new ArrayList();

        All you need to do is type like this List&lt;Integer&gt;list = new ArrayList(); to make it appear as above.

    5. Rajarao Koluru says:

      List list = new ArrayList();
      you can declare in this the code will execute

    6. Naresh Makhija says:


      It’s answer is simple that you are declaring list variable of Object type and then later you are using operator which is not applicable on Object so just change your list type

      List list=new ArrayList();

      That’s it

    7. KChatla says:


      It’s working or nor?

  23. swathi says:

    is streams and streams api are same???

    what will come under streams api?

  24. Saurabh Jain says:

    I am just confused about the answer to question number 41, it should be Tree Map or LinkedHashMap for having the insertion order .

  25. Ankit says:

    Thanks for sharing java 8 new features.

  26. Test says:

    Strangely, I ran the sum example both the conventional way and with Java Stream API. I set the number of elements much higher. The conventional way seems to take lesser time than both serial and parallel streams. So the advantages are not clear to me. Please clarify

  27. priya says:

    what will be the code change of thi FOR in java8:
    int noOfBeers = 0;
    for(Item item: purchasedItems){
    if( item.category == “beer”){
    noOfBeers += item.noOfUnits;
    System.out.println(“Number of beers bought : ” + noOfBeers);

    1. Kazaag says:

      To get the number of beers:

      int noOfBeers =
      .filter(i->i.category == "beer")
      .mapToInt(i -> i.noOfUnits)

  28. viral says:

    Hi Pankaj, Can we use Stream API for filtering object collections based on the object properties ?

  29. Dilip Kumar Pandey says:

    HI Pankaj I follow Your blogs regularly
    Your examples are pricese and upto
    the point
    Pls clarify my following doubt

    Integer[] array = new Integer[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
    for(int i = 0; i 15) System.out.println(“i > 15”);

    code ends:

    can You tell how can we do the same thing using
    Java 8 stream

    1. Pankaj says:

      Stream is for collection, not for array. Also your code didn’t posted correctly, use <code> tag to wrap them.

      1. SJ says:

        Integer[] array = new Integer[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};>i>5).forEach(i->System.out.println(i));

        1. Pankaj says:

          Thanks, i forgot that Arrays class has stream() methods.

          1. SJ says:

            Good Article, I like it. Keep it up Pankaj Bhai.

            Stack Profile

        2. Kazaag says:

          You can also use method reference:


  30. Kumar says:

    There is one problem…in Stateless lambda expressions
    as you said if we use sequential stream we will not get different values but matter of fact , with sequential stream I have got different values….
    [10, 11, 8, 9, 14, 15, 12, 13, 1, 2]
    [10, 4, 11, 5, 6, 7, 8, 1, 9, 2]
    [10, 11, 8, 9, 4, 5, 14, 15, 12, 13]

    you should correct the line. If we use sequential stream, then this problem will not arise.

    1. Pankaj says:

      I am not sure what you are trying to say, I am assuming you are talking about example above. Change it to sequential stream; and you will always get below result.

      [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

  31. ADITYA VALLURU says:

    Hey Pankaj,

    From where did you get this info. man. Its really amazing, its not small task to do. I really appreciate you work. Keep up the good Job.
    Coming to this lesson Steam API, looks amazing to me. Thanks to Java People. Some doubts on symbol like -> to assign values and without declaring a variable you are using it.

    1. Pankaj says:

      Thats the syntax of lambda expressions.

      1. raju says:

        can u tell me about the convert parallel stream to normal stream

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors