본문 바로가기
JAVA

4. 함수형 문법 사용한 예제 2

by leek94 2024. 10. 1.

1. 짝수를 제곱으로 출력

홀수를 세제곱으로 출력

import java.util.List;

public class FP01Exercises {

	public static void main(String[] args) {
		
		List<Integer> numbers = List.of(12,9,13,4,6,2,4,12,15);

		printSquaresOfEvenNumberInLisFunctional(numbers);
		printCubeOfOddNumberInLisFunctional(numbers);
		
	}
	
	private static void printSquaresOfEvenNumberInLisFunctional(List<Integer> numbers) {
		numbers.stream()
			.filter(number -> number%2 == 0) // 람다 표현식
			.map(x -> x * x)
			.forEach(System.out::println);
	}
	
	private static void printCubeOfOddNumberInLisFunctional(List<Integer> numbers) {
		numbers.stream()
			.filter(number -> number%2 == 1) // 람다 표현식
			.map(x -> x * x * x)
			.forEach(System.out::println);
	}
}
144
16
36
4
16
144


729
2197
3375

 

 

2. 문자열의 길이를 출력

public class FP01Exercises {

	public static void main(String[] args) {
    
		List<String> courses = 
            List.of("Spring" , "Spring Boot", "API", "Microservices",
                    "AWS", "PCF", "Azure","Docker", "Kubernetes");

	
		courses.stream()
		.map(course ->course + " " + course.length())
		.forEach(System.out::println);
		}
    }
Spring 6
Spring Boot 11
API 3
Microservices 13
AWS 3
PCF 3
Azure 5
Docker 6
Kubernetes 10

'JAVA' 카테고리의 다른 글

5. Optional에 대한 설명  (1) 2024.10.01
3. 함수형 문법을 사용한 예제  (0) 2024.10.01
2. 함수형 문법 사용 filter()  (0) 2024.10.01
1. 함수형 자바 문법 Stream()  (0) 2024.10.01
스트림 3  (0) 2023.03.03