Convert an Iterable to Stream in Java

JavaObject Oriented ProgrammingProgramming

Let’s say the following is our Iterable −

Iterable<String> i = Arrays.asList("K", "L", "M", "N", "O", "P");

Now, create a Collection −

Stream<String> s = convertIterable(i);

Above, we have a custom method convertIterable() for conversion. Following is the method −

public static <T> Stream<T> convertIterable(Iterable<T> iterable) {
   return StreamSupport.stream(iterable.spliterator(), false);
}

Example

Following is the program to convert an Iterable to Stream in Java −

 Live Demo

import java.util.*;
import java.util.stream.*;
public class Demo {
   public static <T> Stream<T> convertIterable(Iterable<T> iterable) {
      return StreamSupport.stream(iterable.spliterator(), false);
   }
   public static void main(String[] args) {
      Iterable<String> i = Arrays.asList("K", "L", "M", "N", "O", "P");
      Stream<String> s = convertIterable(i);
      System.out.println("Iterable to Stream: "+s.collect(Collectors.toList()));
   }
}

Output

Iterable to Stream: [K, L, M, N, O, P]
raja
Published on 26-Sep-2019 16:35:34
Advertisements