메서드 체이닝 (Method Chaining)은 객체의 메서드 호출 결과로 다시 그 객체를 반환하여 연속적으로 메서드를 호출할 수 있게 하는 프로그래밍 기법이다.
public class Main {
public static void main(String[] args) {
String result = " Hello World ".trim().toUpperCase().replace("WORLD", "JAVA");
System.out.println(result); // HELLO JAVA
}
}
함수형 스타일로 데이터를 필터링, 매핑, 정렬, 집계할 수 있어 간결한 코드 작성이 가능하다. Stream API는 메서드 체이닝을 전제로 하여 연속적인 연산이 가능하다.
Stream API를 사용할 수 있는 객체는 주로 java.util.stream.Stream을 생성할 수 있는 데이터 소스로, List, 배열, Map, Files.lines() 등이 있다.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StockStreamExample {
public static void main(String[] args) {
List<Stock> stocks = Arrays.asList(
new Stock("Apple", 15000),
new Stock("Google", 9000),
new Stock("Microsoft", 20000));
List<String> expensiveStockNames = stocks.stream()
.filter(stock -> stock.getPrice() >= 10000) // 조건 필터링
.map(Stock::getName) // 이름만 추출
.sorted() // 정렬
.collect(Collectors.toList()); // 리스트로 수집
System.out.println(expensiveStockNames); // [Apple, Microsoft]
}
}