HOWTO · Java

Java에서 스트림을 목록으로 변환

이 기사에서는 Java에서 스트림을 목록으로 변환하는 방법을 소개합니다.

이 페이지의 내용

이 튜토리얼은 자바에서 Stream을 List로 변환하는 방법을 소개합니다.

Stream은 객체의 모음입니다. Stream은 데이터를 저장하지 않으므로 데이터 구조가 아닙니다.

Stream은 Java 8 버전에 추가되었지만 List는 정렬된 컬렉션을 저장하는 인터페이스입니다. 이 자습서에서는 스트림을 목록으로 변환하는 방법을 살펴보겠습니다.

Java에는 작업을 수행할 수 있는 다음과 같은 방법이 있습니다.

  • collect() 메소드를 사용하여 변환
  • toCollection() 메서드를 사용하여 변환
  • forEach() 메서드를 사용하여 변환
  • toArray() 메서드를 사용하여 변환

Java에서 collect() 메소드를 사용하여 스트림을 목록으로 변환

스트림 collect() 작업은 터미널 작업입니다. 터미널 작업은 스트림이 소비되고 이 작업 후에 더 이상 사용할 수 없음을 의미합니다.

이 메서드의 구문은 다음과 같습니다.

collect(Collector<? super T, A, R> collector)

이 메서드는 Collector 개체를 인수로 사용합니다.

Collector 클래스는 Stream의 요소를 컬렉션으로 수집하는 데 사용됩니다. 이 클래스에는 스트림을 목록으로 변환하는 toList() 메서드가 있습니다.

이제 코드 예제를 살펴보겠습니다.

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class SimpleTesting {
  public static void main(String args[]) {
    // declaring a stream
    Stream<String> furnitures =
        Stream.of("chair", "dinning table", "study table", "coffee table", "sofa");

    // changing stream to list
    List<String> furniture_list = furnitures.collect(Collectors.toList());

    // printing the list
    for (String furniture : furniture_list) {
      System.out.println(furniture);
    }
  }
}

출력:

chair
dinning table
study table
coffee table
sofa

Java에서 toCollection() 메서드를 사용하여 스트림을 목록으로 변환

이 예제는 Collectors.toCollection() 메서드 대신 Collector.toList() 메서드를 사용한 것을 제외하고 이전 예제와 유사합니다.

Collector 클래스에는 입력 항목을 발생한 순서대로 새 Collection으로 수집하는 Collector를 반환하는 toCollection()이라는 메서드가 있습니다. 아래 예제 코드를 보십시오.

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class SimpleTesting {
  public static void main(String args[]) {
    // declaring a stream
    Stream<String> furnitures =
        Stream.of("chair", "dinning table", "study table", "coffee table", "sofa");

    // changing stream to list
    List<String> furniture_list = furnitures.collect(Collectors.toCollection(ArrayList::new));

    // printing the list
    for (String furniture : furniture_list) {
      System.out.println(furniture);
    }
  }
}

출력:

chair
dinning table
study table
coffee table
sofa

Java에서 forEach() 메소드를 사용하여 스트림을 목록으로 변환

이 예제에서는 먼저 빈 ArrayList를 만든 다음 forEach() 메서드를 사용하여 각 Stream 요소를 List에 하나씩 추가했습니다. Stream에는 입력 Stream의 모든 요소에 대해 수행하는 forEach()라는 메서드가 있습니다.

아래 예제 코드를 보십시오.

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class SimpleTesting {
  public static void main(String args[]) {
    // declaring a stream
    Stream<String> furnitures =
        Stream.of("chair", "dinning table", "study table", "coffee table", "sofa");

    // declaring an empty arraylist
    ArrayList<String> furniture_list = new ArrayList<>();

    // adding elements one by one
    furnitures.forEach(furniture_list::add);

    // printing the list
    for (String furniture : furniture_list) {
      System.out.println(furniture);
    }
  }
}

출력:

chair
dinning table
study table
coffee table
sofa

Java에서 toArray() 메서드를 사용하여 스트림을 목록으로 변환

이 예제에서는 먼저 toArray() 메서드를 사용하여 Stream을 배열로 변환했습니다. 그런 다음 asList() 메서드를 사용하여 새로 생성된 배열을 List로 변환하여 목록을 얻습니다.

아래 코드를 보세요.

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class SimpleTesting {
  public static void main(String args[]) {
    // declaring a stream
    Stream<String> furnitures =
        Stream.of("chair", "dinning table", "study table", "coffee table", "sofa");

    // converting stream to array
    String[] furniture_array = furnitures.toArray(String[] ::new);

    // converting array to list
    List<String> furniture_list = Arrays.asList(furniture_array);

    // printing the list
    for (String furniture : furniture_list) {
      System.out.println(furniture);
    }
  }
}

출력:

chair
dinning table
study table
coffee table
sofa