Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Program to Iterate over a Stream with Indices in Java 8
Next article icon

Program to Iterate over a Stream with Indices in Java 8

Last Updated : 11 Dec, 2018
Comments
Improve
Suggest changes
Like Article
Like
Report
Given a Stream in Java, the task is to iterate over it with the help of indices. Examples:
Input: Stream = [G, e, e, k, s] Output: [0 -> G, 1 -> e, 2 -> e, 3 -> k, 4 -> s] Input: Stream = [G, e, e, k, s, F, o, r, G, e, e, k, s] Output: [0 -> G, 1 -> e, 2 -> e, 3 -> k, 4 -> s, 5 -> F, 6 -> o, 7 -> r, 8 -> G, 9 -> e, 10 -> e, 11 -> k, 12 -> s]
  • Method 1: Using IntStream.
    1. Get the Stream from the array using range() method.
    2. Map each elements of the stream with an index associated with it using mapToObj() method
    3. Print the elements with indices
    Java
    // Java program to iterate over Stream with Indices  import java.util.stream.IntStream;  class GFG {     public static void main(String[] args)     {          String[] array = { "G", "e", "e", "k", "s" };          // Iterate over the Stream with indices         IntStream              // Get the Stream from the array             .range(0, array.length)              // Map each elements of the stream             // with an index associated with it             .mapToObj(index -> String.format("%d -> %s",                                         index, array[index]))              // Print the elements with indices             .forEach(System.out::println);     } } 
    Output:
      0 -> G  1 -> e  2 -> e  3 -> k  4 -> s  
  • Method 2: Using AtomicInteger.
    1. Create an AtomicInteger for index.
    2. Get the Stream from the array using Arrays.stream() method.
    3. Map each elements of the stream with an index associated with it using map() method where the index is fetched from the AtomicInteger by auto-incrementing index everytime with the help of getAndIncrement() method.
    4. Print the elements with indices.
    Java
    // Java program to iterate over Stream with Indices  import java.util.stream.IntStream; import java.util.*; import java.util.concurrent.atomic.AtomicInteger;  class GFG {     public static void main(String[] args)     {          String[] array = { "G", "e", "e", "k", "s" };          // Create an AtomicInteger for index         AtomicInteger index = new AtomicInteger();          // Iterate over the Stream with indices         Arrays              // Get the Stream from the array             .stream(array)              // Map each elements of the stream             // with an index associated with it             .map(str -> index.getAndIncrement() + " -> " + str)              // Print the elements with indices             .forEach(System.out::println);     } } 
    Output:
      0 -> G  1 -> e  2 -> e  3 -> k  4 -> s  

Next Article
Program to Iterate over a Stream with Indices in Java 8

R

RishabhPrabhu
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

    Program to convert a Set to Stream in Java using Generics
    Java Set is a part of java.util package and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element. A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.
    3 min read
    Convert an Iterator to Stream in Java
    Given an Iterator, the task is to convert it into Stream in Java. Examples: Input: Iterator = {1, 2, 3, 4, 5} Output: {1, 2, 3, 4, 5} Input: Iterator = {'G', 'e', 'e', 'k', 's'} Output: {'G', 'e', 'e', 'k', 's'} Approach: Get the Iterator. Convert the iterator to Spliterator using Spliterators.split
    1 min read
    Convert an Iterable to Stream in Java
    Given an Iterable, the task is to convert it into Stream in Java. Examples: Input: Iterable = [1, 2, 3, 4, 5] Output: {1, 2, 3, 4, 5} Input: Iterable = ['G', 'e', 'e', 'k', 's'] Output: {'G', 'e', 'e', 'k', 's'} Approach: Get the Iterable. Convert the Iterable to Spliterator using Iterable.spliterat
    1 min read
    Stream iterate(T,Predicate,UnaryOperator) method in Java with examples
    The iterate(T, java.util.function.Predicate, java.util.function.UnaryOperator) method allows us to iterate stream elements till the specified condition. This method returns a sequential ordered Stream produced by iterative application of the given next function to an initial element, conditioned on
    2 min read
    Stream.of(T t) in Java with examples
    Stream of(T t) returns a sequential Stream containing a single element i.e, a singleton sequential stream. A sequential stream work just like for-loop using a single core. On the other hand, a Parallel stream divide the provided task into many and run them in different threads, utilizing multiple co
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences