Monday, April 3, 2023

How to use Stream range, rangeClosed, sum and sorted methods? Java 8 IntStream Examples -

Hello guys, if you want to learn about IntStream in Java 8 and looking for a simple tutorial and example then you have come to the right place. Earlier, I have shared 10 examples of Lambda expression and filter+ map+ collect examples and in this article, I will show you how to use IntStream in Java 8. IntStream is a specialization of Stream class for primitive int values. It allows you to perform a sequential and parallel aggregate operation on a list of values like count() to print the total number of element in stream, min() to find minimum value in the stream, max() to find maximum value in the stream, sum() to find a total of all values and average() to find the average of all numbers in the stream.

It is very useful while you are operating on numeric data. You can create IntStream of specific values by using IntStream.of() static factory method, or you can convert any stream to IntStream by using the mapToInt() function, which is extremely useful to convert numeric String into primitive int and then performing these aggregate and grouping operations.

Stream API also provides a couple of utility method to create a sequence of string in a specific range like IntStream.range(strat, endExclusive) and IntStream.rangeClosed(start, endInclusive) can be used to create a sequence of integers incremented by 1 like range(1, 5) will produce 1, 2, 3, 4 because last value is exclusive, while rangeClosed(1, 5) will produce 1, 2, 3, 4, 5. 

That is also the only difference between the range() and rangeClosed() method. Btw, if you are new to Java programming then I highly recommend you to join a comprehensive Java course to learn in a structured way. If you need a recommendation then I suggest you join The Complete Java Masterclass by Tim Buchalaka and his team on Udemy. This 80-hour long course is most up-to-date and also very affordable, you can buy in just $10 on Udemy sales. 




Some important methods of IntStream class

Here are some of the important methods of IntStream class from Java 8:
  • rangeClosed(a,b):  values from a to be are considered by incrementing 1.
  • range(a,b) : values from a to b-1 are considered.
  • sum:  calculates the sum of values.
  • sorted: values are sorted.
  • max - for calculating maximum value
  • min - for minimum value
  • average- for calculating the average. 
You also need to remember that most of the IntStream functions are terminal operations, especially the numeric and aggregation ones and once you apply a terminal function on Stream you cannot reuse it. If you try to perform another operation on stream after performing terminal operation then you will get the following error:

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
at java.util.stream.AbstractPipeline.(AbstractPipeline.java:203)
at java.util.stream.LongPipeline.(LongPipeline.java:91)
at java.util.stream.LongPipeline$StatelessOp.(LongPipeline.java:572)
at java.util.stream.IntPipeline$5.(IntPipeline.java:261)
at java.util.stream.IntPipeline.mapToLong(IntPipeline.java:260)
at java.util.stream.IntPipeline.count(IntPipeline.java:429)



And, if you want to learn more about Stream API in Java 8, then I highly recommend you to join Learn Java Functional Programming with Lambdas & Streams course by Ranga Karnam from Udemy. It's a great course to learn both Functional programming and Stream API in Java 8. 

Java 8 IntStream Examples - range, rangeClosed, sum and sorted





How to use range, rangeClosed, sum, and sorted() of IntStream in Java 8

Here is our complete Java program to demonstrate how to create IntStream in Java 8 and how to use its variable methods like range() and the rangeClosed() for generating integer sequences and its aggregation and grouping function to calculate maximum, minimum, and average values.  


package test;
 
 
 
import java.util.Arrays;
 
import java.util.List;
 
import java.util.stream.IntStream;
 
 
 
/**
 
 * Java 8 IntStream example. IntStream is a specialized version of Stream class
 
 * for integers. It's useful to perform aggregate and grouping function like
 
 * count(), sum(), min() and max.
 
 * @author Javin
 
 */
 
public class Test {
 
 
 
    public static void main(String args[]) {
 
 
 
         // You can create int stream of given values
 
        IntStream iStream = IntStream.of(1, 2, 3, 4, 5, 6);
 
        System.out.println("IntStream created using static factory method : ");
 
        iStream.forEach(System.out::println); //1 2 3 4 5
 
 
 
 
 
        // You can also create IntStream by using rangeClose() and range()
 
        // method. range() method returns an stream of increasing int in
 
        // given range
 
        iStream = IntStream.range(10, 18);
 
        System.out.println("IntStream created using static factory method : ");
 
        iStream.forEach(System.out::println); // 10, 11, 12, 13, 14, 15, 16, 17
 
 
 
        // in rangeClosed() end number is also inclusive
 
        iStream = IntStream.rangeClosed(20, 25);
 
        System.out.println("IntStream created using static factory method : ");
 
        iStream.forEach(System.out::println); // 20, 21, 22, 23, 24, 25
 
 
 
 
 
        // You can also create IntStream by using mapToInt() function
 
        List listOfNumbers = Arrays.asList("41", "42", "43", "44");
 
        System.out.println("input list : " + listOfNumbers);
 
        IntStream fromMapping = listOfNumbers.stream().mapToInt(Integer::valueOf);
 
 
 
        // you can apply mathematicall aggregate function like forEach(), min()
 
        // max() and avg() on stream of int values
 
        System.out.println("total number of numbers using count :" + fromMapping.count());
 
 
 
        // Now we need another stream because after calling count() stream
 
        // is closed and cannot be used anymore
 
 
 
        System.out.println("maximum value in stream : "
 
                + listOfNumbers.stream().mapToInt(Integer::valueOf).max());
 
        System.out.println("minimum value in list : "
 
                + listOfNumbers.stream().mapToInt(Integer::valueOf).min());
 
        System.out.println("sum of all numbers in list : "
 
                + listOfNumbers.stream().mapToInt(Integer::valueOf).sum());
 
        System.out.println("average of all numbers in list : "
 
                + listOfNumbers.stream().mapToInt(Integer::valueOf).average());
 
 
 
 
 
        // max() and min() function return Optional, if you need integer
 
        // output, you can do like this
 
        int max = listOfNumbers.stream()
 
                               .mapToInt(Integer::valueOf)
 
                               .max()
 
                               .getAsInt();
 
 
 
        int min = listOfNumbers.stream()
 
                               .mapToInt(Integer::valueOf)
 
                               .min()
 
                               .getAsInt();
 
 
 
        double avg = listOfNumbers.stream()
 
                                  .mapToInt(Integer::valueOf)
 
                                  .average()
 
                                  .getAsDouble();
 
        System.out.println("maxium value in list : " + max);
 
        System.out.println("minimum value in list : " + min);
 
        System.out.println("avg of all values in list : " + avg);
 
    }
 
 
 
 
 
 
 
}
 
 
 
 
 
Output :
 
run:
 
IntStream created using static factory method :
 
1
 
2
 
3
 
4
 
5
 
6
 
IntStream created using static factory method :
 
10
 
11
 
12
 
13
 
14
 
15
 
16
 
17
 
IntStream created using static factory method :
 
20
 
21
 
22
 
23
 
24
 
25
 
input list : [41, 42, 43, 44]
 
total number of numbers using count :4
 
maximum value in stream : OptionalInt[44]
 
minimum value in list : OptionalInt[41]
 
sum of all numbers in list : 170
 
average of all numbers in list : OptionalDouble[42.5]
 
maxium value in list : 44
 
minimum value in list : 41
 
avg of all values in list : 42.5
 
 
I have directly printed the Optional but if you want you can also retrieve the actual values from Optional using the Optional.get() method as shown in this Optional Examples article. 


Second Example of IntStream using Object

package test;
 
 
import java.util.ArrayList;
import java.util.Arrays;
 
import java.util.List;
 
import java.util.stream.IntStream;
 
 
 
/**
 
 * Java 8 IntStream example. IntStream is a specialized version of Stream class
 
 * for integers. It's useful to perform aggregate and grouping function like
 
 * count(), sum(), min() and max.
 
 * @author Javin
 
 */
 
public class Test {
 
 
 
    public static void main(String args[]) {
 
 
 
        // Now let's see some IntStream examples with objects with filter
 
        List candidates = new ArrayList<>();
 
        candidates.add(new Student("John", 33));
 
        candidates.add(new Student("Jack", 11));
 
        candidates.add(new Student("Rick", 50));
 
        candidates.add(new Student("Shane", 90));
 
 
 
 System.out.println("list of candidates : " + candidates);
 
 
 
        // Now let's print name of topper
 
        int highestMarks = candidates.stream()
 
                                     .mapToInt(s -> s.getMarks())
 
                                     .max().getAsInt();
 
        System.out.println("highest marks : " + highestMarks);
 
 
 
        long numOfPassCandidates = candidates.stream()
 
                                            .filter(c -> c.getMarks() >= 33)
 
                                            .count();
 
        System.out.println("Number of pass candidates : " + numOfPassCandidates);
 
 
 
        int lowestMarks = candidates.stream()
 
                                     .mapToInt(s -> s.getMarks())
 
                                     .min().getAsInt();
 
        System.out.println("lowest marks : " + lowestMarks);
 
 
 
        double avgMarksOfPassedStudents = candidates.stream()
 
                                                    .filter(c -> c.getMarks() >= 33)
 
                                                    .mapToInt( c -> c.getMarks())
 
                                                    .average().getAsDouble();
 
        System.out.println("Average marks of all passed candidates : " 
                                      + avgMarksOfPassedStudents);
 
    }
 
 
 
 
 
 
 
}
 
 
 
class Student{
 
    String name; ;
 
    int marks;
 
 
 
    public Student(String name, int marks){
 
        this.name = name;
 
        this.marks = marks;
 
    }
 
 
 
    public String getRollnumber(){
 
        return name;
 
    }
 
 
 
    public int getMarks(){
 
        return marks;
 
    }
 
 
 
    @Override
 
    public String toString(){
 
        return String.format("[%s, %d]", name, marks);
 
    }
 
}
 
 
 
Output :
 
list of candidates : [[John, 33], [Jack, 11], [Rick, 50], [Shane, 90]]
 
highest marks : 90
 
Number of pass candidates : 3
 
lowest marks : 11
 
Average marks of all passed candidates : 57.666666666666664


That's all about how to use the IntStream example in Java 8. In this article, I have shown you how you can create a stream of integer values and how you can use IntStream class to calculate aggregation and grouping like calculating maximum, minimum, sum, and average from a list of values. 

Other Java Functional Programming tutorials you may like

No comments:

Post a Comment