Core Java

Java 8 IntStream With Working Examples

A quick guide to understand primitive int representation of Stream as interface IntStream to support integer operations and with the useful examples.

1. Overview

In this tutorial, We’ll learn how to use the IntStream in java 8 and it uses with example programs.

For int primitives, the Java IntStream class is a specialization of the Stream interface. It’s a stream of primitive int-valued items that can be used in both sequential and parallel aggregate operations.

AutoCloseable and BaseStream interfaces are implemented by IntStream, which is part of the java.util.stream package.

We will learn the following topics in this course.

  • IntStream Creation
  • ForEach loop
  • IntStream ranges
  • IntStream min and max
  • IntStream find
  • IntStrem map
  • IntStream filter
  • IntStream distinct
  • IntStream to Array
  • IntStream to List

2. Creating IntStream

An IntStream can be generated in a variety of ways, but it cannot be created using a new keyword.

The IntStream objects are created using the methods listed below.

  • IntStream.of()
  • IntStream.range()
  • IntStream.rangeclosed()
  • IntStream.generate()
  • IntStream.iterate()

Let us explore the ways to use these methods with example programs. to create an instance for IntStream with primitive int values.

2.1 IntStream.of()

This function returns a sequentially ordered stream with the provided values as its elements.

It is available in two forms: single element stream and multiple values stream.

IntStream of(int t) – Returns a stream consisting of a single supplied element.

IntStream of(int… values) – Returns a stream with all the components supplied.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
package com.javaprogramto.java8.intstream;
 
import java.util.stream.IntStream;
 
public class IntStreamOf {
 
    public static void main(String[] args) {
 
        IntStream singleValue = IntStream.of(10);
 
        IntStream multipleValeus = IntStream.of(1, 5, 10, 20, 30);
 
    }
 
}

2.2 IntStream.range()

range() is used to generate the numbers in the order with incremental by one.

static IntStream range(int startInclusive, int endExclusive) — here the end range is exclusive.

1
IntStream range10to30 = IntStream.range(10, 20);

2.3 IntStream.rangeclosed()

rangeClosed() is also used to generate the numbers in the order with incremental by one but it includes the end index of this method.

static IntStream rangeClosed(int startInclusive, int endInclusive)

1
IntStream range10to15closed = IntStream.range(10, 15);

2.4 IntStream.generate()

Use the generate() method if you wish to generate random numbers with custom logic.

1
IntStream random = IntStream.generate( () -> { return (int) Math.random() * 5000;});

2.5 IntStream.iterate()

The iterate() method is identical to the generate() method, except instead of random values, it uses incremental or decrement custom logic for large values.

Due to the fact that the iterate() method generates an infinite stream of integers, you must use the limit() function to get the first n numbers.

1
IntStream iterate = IntStream.iterate(1000, i -> i + 4000).limit(5);

3. IntStream forEach()

Typically we can use the traditional for loop for certain range. However, the same thing may be accomplished by using the IntStream.forEach() function instead.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.javaprogramto.java8.intstream;
 
import java.util.stream.IntStream;
 
public class IntStreamOf {
 
    public static void main(String[] args) {
         
        System.out.println("for loop");
        for(int i = 1000; i < 20000 ; i = i + 4000) {
            print(i);
        }
         
        System.out.println("intstream foreach loop");
        IntStream iterate = IntStream.iterate(1000, i -> i + 4000).limit(5);
         
        iterate.forEach(n -> print(n));
         
         
    }
     
    private static void print(int n) {
        System.out.println(n);
    }
 
}

4. IntStream ranges 

Two methods are offered by the IntStream API to work with numbers generated in a defined range.

range(start, endExclusive): excludes the end index from the output range.

rangeClosed(start, endInclusive): this method includes the end index from the output range.

The below program output gives you clear understanding between range() and rangeClosed() methods.

1
2
3
4
5
IntStream range10to15range = IntStream.range(10, 15);
        IntStream range10to15closed = IntStream.rangeClosed(10, 15);
         
        System.out.println("range(10, 15) : "+Arrays.toString(range10to15range.toArray()));
        System.out.println("rangeClosed(10, 15) : "+Arrays.toString(range10to15closed.toArray()));

Output:

1
2
range(10, 15) : [10, 11, 12, 13, 14]
rangeClosed(10, 15) : [10, 11, 12, 13, 14, 15]

5. IntStream min and max

IntStream has utility methods for determining the minimum and maximum values from a series of numbers or random numbers.

Use min() method to retrieve the lowest value from int stream.

Use max() method to retrieve the highest value from int stream.

1
2
System.out.println("range(10, 15) min value : "+IntStream.range(10, 15).min().getAsInt());
System.out.println("range(10, 15) max value : "+IntStream.range(10, 15).max().getAsInt());

Output:

1
2
range(10, 15) min value : 10
range(10, 15) max value : 14

6. IntStream find value

Use findFirst() or findAny() methods on the InstStream object to get the first or any value.

findFirst() vs findAny() indepth

By default, IntStream is created as sequential stream unless call the parallel() on the IntStream.

For sequential streams, the findFirst() and findAny() methods return the same result. If the stream is parallel, however, the findAny() method gives a random value.

1
2
3
4
System.out.println("findFirst value : "+IntStream.iterate(10, i -> i + 2).limit(100).findFirst().getAsInt());
System.out.println("findAny value : "+IntStream.iterate(10, i -> i + 2).limit(100).findAny().getAsInt());
 
System.out.println("parallel findAny value : "+IntStream.iterate(10, i -> i + 2).limit(100).parallel().findAny().getAsInt());

Output:

1
2
3
findFirst value : 10
findAny value : 10
parallel findAny value : 160

7. IntStream map() or flatMap()

We can transform the IntStream into the new form using map() method but flatMap() method does the flatten the IntStreams into primitives.

Usage of map() and flatMap() does not give much difference with IntStream usage.

01
02
03
04
05
06
07
08
09
10
11
12
IntStream mapInput = IntStream.iterate(10, i -> i + 1).limit(10);
 
System.out.println("map input stream : "+Arrays.toString(mapInput.toArray()));
 
IntStream mapOutput = mapInput.map( i -> i * 2);
 
System.out.println("map Output stream : "+Arrays.toString(mapOutput.toArray()));
 
 
IntStream input1 = IntStream.iterate(10, i -> i + 1).limit(10);
 
System.out.println("flat map : "+Arrays.toString(input1.flatMap( i -> IntStream.of(i)).toArray()));

Output:

1
2
3
map input stream : [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
map Output stream : [20, 22, 24, 26, 28, 30, 32, 34, 36, 38]
flat map : [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

8. IntStream filter

Use filter() method to filter the integer values based on the given IntPredicate condition.

After applying the filter() method then next you can call forEach() or collect() method to convert it into List or Set.

01
02
03
04
05
06
07
08
09
10
11
IntStream stream = IntStream.range(100, 200);
 
// filter by number divisible by 5 and 7
System.out.println("numbers divisible by 5 and 7 are : ");
stream.filter(i -> (i % 5 == 0 && i % 7 == 0)).forEach(System.out::println);
 
IntStream stream2 = IntStream.range(100, 200);
 
List<Integer> primes = stream2.filter(IntStreamOf::checkPrime).boxed().collect(Collectors.toList());
 
System.out.println("Prime numbers (100, 200) are "+primes);

Output:

1
2
3
4
5
numbers divisible by 5 and 7 are :
105
140
175
Prime numbers (100, 200) are [101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199]

9. IntStream distinct()

Use distinct() method to remove the duplicate values from IntStream.

1
Arrays.toString(IntStream.of(1, 2, 3, 1, 2, 3).distinct().toArray());

Output:

1
[1, 2, 3]

10. IntStream to Array and List or Set

Use toArray() method to collect the output of IntStream into Array.

Use collect() method to collect the output of IntStream into List or Set.

To remove the duplicates from int stream, you can collect the results into Set rather than using distinct() method. But distinct() is recommended.

1
2
3
4
5
6
7
8
9
int[] intArray = IntStream.of(1, 2, 3, 1, 2, 3).toArray();
System.out.println("int array : "+Arrays.toString(intArray));
 
 
List<Integer> list = IntStream.of(1, 2, 3, 1, 2, 3).boxed().collect(Collectors.toList());
System.out.println("IntStream to List : "+list);
 
Set<Integer> set = IntStream.of(1, 2, 3, 1, 2, 3).boxed().collect(Collectors.toSet());
System.out.println("IntStream to Set : "+set);

11. Conclusion

In this article, we have seen all useful methods of IntStream with the useful examples.

GitHub

IntStream API

Published on Java Code Geeks with permission by Venkatesh Nukala, partner at our JCG program. See the original article here: Java 8 IntStream With Working Examples

Opinions expressed by Java Code Geeks contributors are their own.

Venkatesh Nukala

Venkatesh Nukala is a Software Engineer working for Online Payments Industry Leading company. In my free time, I would love to spend time with family and write articles on technical blogs. More on JavaProgramTo.com
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Alexandre
1 year ago

Excellent tutorial and when I started to read it I saw the item 2.3 with rangeClosed() but in your code you wrote only range()

Govardhan
Govardhan
7 months ago

small mistake it seems.2.3 IntStream.rangeclosed()

1

Given -->IntStream range10to15closed = IntStream.range(

10

,

15

);

1

should be --> IntStream range10to15closed = IntStream.rangeClosed(

10

,

15

);

Back to top button