Convert an Iterable to Collection in Java

JavaObject Oriented ProgrammingProgramming

Let’s say the following is our Iterable −

Iterable<Integer> i = Arrays.asList(50, 100, 150, 200, 250, 300, 500, 800, 1000);

Now, create a Collection −

Collection<Integer> c = convertIterable(i);

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

public static <T> Collection<T> convertIterable(Iterable<T> iterable) {
   if (iterable instanceof List) {
      return (List<T>) iterable;
   }
   return StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList());
}

Example

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

 Live Demo

import java.util.*;
import java.util.stream.*;
public class Demo {
   public static <T> Collection<T> convertIterable(Iterable<T> iterable) {
      if (iterable instanceof List) {
         return (List<T>) iterable;
      }
      return StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList());
   }
   public static void main(String[] args) {
      Iterable<Integer> i = Arrays.asList(50, 100, 150, 200, 250, 300, 500, 800, 1000);
      Collection<Integer> c = convertIterable(i);
      System.out.println("Collection (Iterable to Collection) = "+c);
   }
}

Output

Collection (Iterable to Collection) = [50, 100, 150, 200, 250, 300, 500, 800, 1000]
raja
Published on 26-Sep-2019 13:03:20
Advertisements