$show=/label

Java 8 IntStream With Working Examples

SHARE:

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
Java 8 IntStream With Working Examples


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.
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.

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)
IntStream range10to15closed = IntStream.range(10, 15);
 

2.4 IntStream.generate()


Use the generate() method if you wish to generate random numbers with custom logic.
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.
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.
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.
		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:
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.
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:
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.


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.
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:
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.
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:
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.
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:
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.
Arrays.toString(IntStream.of(1, 2, 3, 1, 2, 3).distinct().toArray());
 
Output:
[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.
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.



COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,17,Arrays,16,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,29,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,93,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,35,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,14,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,30,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,111,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,105,Java Spark,1,java.lang,5,java.util. function,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,1,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,2,Math,1,Matrix,5,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,28,String,59,String Programs,12,String Revese,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 IntStream With Working Examples
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.
https://1.bp.blogspot.com/-DHTlieK7wb8/YMYlhC0SNQI/AAAAAAAADVE/TNwuN3pdce4HIFY_WFmWmAqgaeX9TD6HQCLcBGAsYHQ/w400-h325/Java%2B8%2BIntStream%2BWith%2BWorking%2BExamples.png
https://1.bp.blogspot.com/-DHTlieK7wb8/YMYlhC0SNQI/AAAAAAAADVE/TNwuN3pdce4HIFY_WFmWmAqgaeX9TD6HQCLcBGAsYHQ/s72-w400-c-h325/Java%2B8%2BIntStream%2BWith%2BWorking%2BExamples.png
JavaProgramTo.com
https://www.javaprogramto.com/2021/06/java-8-intstream-examples.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2021/06/java-8-intstream-examples.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content