Pages

Wednesday, May 6, 2020

Java 8 - How to convert Iterator to Stream

1. Introduction


In this tutorial, You'll learn how to convert Iterator to Stream in java 8. Actually, Iterator does not have a utility method to convert to Stream.

To achieve this, you should a set of classes and those are Spliterators and StreamSupport classes.

Check out latest Articles on Java

2. Example To convert Iterator to Stream in Java 8


When you work with the collection api, you mostly have seen many times using the iterator for getting the values from List or Set through the iterator.


But, in some cases, you get the Iterator when you other api's. Then you want to convert it to as stream and next you can apply map and reduce on stream objects.

Let us jump into an example where First covert the List to Iterator next then Iterator to Stream.

Finally, perform some filtering on the Stream objects.


package com.javaprogramto.java8.streams.conversions;

import com.javaprogramto.models.Employee;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class IteratorToStream {

    public static void main(String[] args) {

        List<Employee> list = new ArrayList<>();

        list.add(new Employee(100, "Santa Clara", 30));
        list.add(new Employee(101, "Sameera Bell", 25));
        list.add(new Employee(102, "Jhon Cena", 33));
        list.add(new Employee(103, "Tubel Nohn", 35));
        list.add(new Employee(104, "Meen Joseph", 31));

        System.out.println("original List : " + list);

        /*        List to Iterator         */        Iterator<Employee> it = list.iterator();

        /*        Iterator to Spliterator         */        Spliterator<Employee> employeeSpliterator = Spliterators.spliteratorUnknownSize(it, Spliterator.ORDERED);

        /*        Spliterator to Stream         */        Stream<Employee> employeeStream = StreamSupport.stream(employeeSpliterator, false);


        List<Employee> ageGt30List = employeeStream.peek(e -> System.out.println(e)).filter(e -> e.getAge() > 30).collect(Collectors.toList());

        System.out.println("Employee age > 30 size: " + ageGt30List.size());
        System.out.println("Employee age > 30 : " + ageGt30List);


    }
}

Output:

original List : [Employee{id=100, fullName='Santa Clara', age=30}, Employee{id=101, fullName='Sameera Bell', age=25}, Employee{id=102, fullName='Jhon Cena', age=33}, Employee{id=103, fullName='Tubel Nohn', age=35}, Employee{id=104, fullName='Meen Joseph', age=31}]

Employee{id=100, fullName='Santa Clara', age=30}

Employee{id=101, fullName='Sameera Bell', age=25}

Employee{id=102, fullName='Jhon Cena', age=33}

Employee{id=103, fullName='Tubel Nohn', age=35}

Employee{id=104, fullName='Meen Joseph', age=31}

Employee age > 30 size: 3

Employee age > 30 : [Employee{id=102, fullName='Jhon Cena', age=33}, Employee{id=103, fullName='Tubel Nohn', age=35}, Employee{id=104, fullName='Meen Joseph', age=31}]


3. Example to Iterator to Stream - Utility Method


Just wrapping the code to convert Iterator to Stream as utility function so that you can any type of iterator and that should produce the Stream<T>

package com.javaprogramto.java8.streams.conversions;

import com.javaprogramto.models.Employee;

import java.util.*;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class IteratorToStreamUtility {

    public static void main(String[] args) {

        List<Employee> list = new ArrayList<>();

        list.add(new Employee(200, "Momanth Soraga", 30));
        list.add(new Employee(201, "Fidha Lady", 25));

        Stream<Employee> empStream = convertIteratorToStream(list);


        System.out.println("Employee Stream Count : " + empStream.count());

        List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

        Stream<Integer> intStream  = convertIteratorToStream(intList);

        System.out.println("Integer Stream Count : " + intStream.count());

        List<String> countiresList = Arrays.asList("USA", "India","UK","AUS");

        Stream<String> countiresStream  = convertIteratorToStream(countiresList);

        System.out.println("String countries Stream Count : " + countiresStream.count());



    }

    /**     * Generic method to take any value List type and return a 
generic Stream.   
  * <p>

     * Main goal to convert Iterator to Stream.     *  
   * @param source     * @param <T>     * @return     */
    public static <T> Stream<T> convertIteratorToStream(List<T> source) {

         /*        List to Iterator         */

        Iterator<T> it = source.iterator();

        /*
        Iterator to Spliterator         */
        Spliterator<T> spliterator = Spliterators.spliteratorUnknownSize(it, Spliterator.ORDERED);

        /*
        Spliterator to Stream         */
        Stream<T> oututStream = StreamSupport.stream(spliterator, false);

        return oututStream;
    }
}

Output:


[Employee Stream Count : 2
Integer Stream Count : 9
String countries Stream Count : 4]


The above code works for all types of Lists, We have shown the examples for List<Employee>, List<Integer> and List<String>

4. Conclusion


In this article, You've seen how to convert Iterator<T> to Stream<T> using Spliterators.spliteratorUnknownSize()  and StreamSupport.stream() methods.

And also shown how to create a generic method that takes any List<T> and produces a Stream<T>.


All the code is shown in this article is over GitHub.

You can download the project directly and can run in your local without any errors.



If you have any queries please post in the comment section.


Java 8 - Iterator to Stream

No comments:

Post a Comment

Please do not add any spam links in the comments section.