Java 프로그래밍에서 Iterable은 요소를 순회할 수 있는 가장 기본적인 인터페이스이며, Collection은 List, Set 등 다양한 자료구조의 상위 인터페이스입니다. Iterable 타입으로 전달받은 데이터를 Collection으로 변환하면 add(), remove(), size() 같은 편리한 메서드를 자유롭게 활용할 수 있습니다.
변환 방법 개요
먼저 다음과 같은 Iterable이 있다고 가정해 보겠습니다.
Iterable<Integer> i = Arrays.asList(50, 100, 150, 200, 250, 300, 500, 800, 1000);
이제 이 Iterable을 Collection으로 변환합니다.
Collection<Integer> c = convertIterable(i);
위 코드에서 호출된 convertIterable()은 직접 작성한 커스텀 메서드로, 다음과 같이 구현합니다.
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());
}메서드 동작 원리
- instanceof 검사: 입력받은 iterable이 이미 List 타입이라면 별도의 변환 과정 없이 캐스팅하여 그대로 반환합니다. 이를 통해 불필요한 객체 복사를 줄여 성능을 높일 수 있습니다.
- StreamSupport 활용: List가 아닌 경우에는 spliterator()로 스트림을 생성한 뒤, collect(Collectors.toList())를 호출하여 새로운 List 형태의 Collection을 만들어 반환합니다.
전체 예제 코드
다음은 Java에서 Iterable을 Collection으로 변환하는 전체 프로그램입니다.
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);
}
}실행 결과
Collection (Iterable to Collection) = [50, 100, 150, 200, 250, 300, 500, 800, 1000]
실행 결과를 보면 Iterable에 담겨 있던 모든 정수 값이 Collection으로 성공적으로 변환된 것을 확인할 수 있습니다. 이 메서드는 제네릭(<T>)을 사용하므로 Integer뿐만 아니라 String 등 어떤 타입의 Iterable에도 그대로 재사용할 수 있다는 장점이 있습니다.