본문 바로가기

콤퓨타/Programming) 왕초보 자바

33. (Arrays) Int Stream

 

지난번 반복문 마치면서 Stream을 배웠던 것 같은데,

강의가 몇회 지나기도 전에 선생님이 다시 이 개념을 반복했다. 

"어려운 개념이지만, 지금 미리 좀 해놔서 나중에 갑자기 나와도 멘탈이 무너지지 않도록 해보자." 라고 하시며 알려주심. 

for 문 대신에 쓸 수 있는 내용인데,

간단한 내용일 경우 동일하게 결과가 나오지만 복잡해지면 for문 대신 아주 유용하게 쓸 수 있는 모양이다. 

다만 선생님이 자꾸 '나중을 대비해서 연습하자' 이러셔서 챗지피티와 해당 부분만 내용 변경 + 난이도 변경해가며 높은 빈도로 연습계속 할 예정. 

 

특이사항은 없고, 

여기서 나오는 .length는 배열 데이터를 가져오는것이며

.map 의 경우 값을 반대로 읽어내는 것

Stream 사용할 때 Control + Shift + O 버튼 통해 java.util.stream.IntStream; 임포트 

 

 

import java.util.stream.IntStream;

public class App {
	
	public static void main(String[]args) {
		// 수업목적: 좀 어려운 syntax 이지만, 지금 좀 미리 해놓자
	
		String[] animals = {"cat", "dog", "sloth", "elephant"}; 
		
		IntStream.range(0, animals.length).forEach(i -> {
			System.out.printf("%d. %s\n", i , animals[i]);
		}); 
		
		//for (int i = 0; i< animals.length; i++) {
		//	System.out.printf("%d. %s\n", i, animals[i]);
		//}
	
	}

}

 

그 결과값 

 

 


연습문제 1

package IntStream;

import java.util.stream.IntStream;

public class Parctice_02 {

	public static void main(String[]args) { 
		IntStream.range(0, 5).forEach(i -> { 
			//System.out.print(i);
			//System.out.println(i);
		System.out.printf("심판 %d 점수: 최고 \n", i);
		
		}); 
	}
}

 

 

 

 

연습문제 2

  • fruits 배열을 만들고 {"apple", "banana", "cherry"} 라는 값을 넣으세요. 
  • 그리고 번호랑 함께 출력하세요. (for문 버전 + IntStream 버전 둘 다)
package IntStream;

public class Practice_03  {
	
	public static void main (String[]args) {
		
		String[] fruit = {"apple", "banana", "cherry"}; 
		for (int i = 0; i < fruit.length; i++) { 
			System.out.printf("%d. 제고과일 명: 시원하고 달달한 %s.\n", i, fruit[i]);
		} 
	}

}

 

 

 

 

 

package IntStream;

import java.util.stream.IntStream;

public class Practice_03  {
	public static void main (String[]args) {
		
		String[]fruit = {"apple", "banana", "cherry"}; 
		
		IntStream.range(0, fruit.length).forEach(i -> { 
		System.out.printf("%d. 발주 예정 과일: %s \n", i, fruit[i]);				
				});
		
	}
}

 

 

 

 

연습문제 3

  • fruits 배열을 역순으로 출력
  • (for문이랑 Stream 두 버전 모두 가능)

 

package IntStream;

public class Practice_04 {
 
	public static void main (String[]args) {
		
		String[] fruits = {"apple", "banana", "cherry", "peach", "blueberry"}; 
		for(int i = 4; i >=0 ; i--) {
			System.out.printf("우리가 좋아하는 과일 %d 위!: %s! \n", i, fruits[i]);
		}
		
	}

}

 

for(int i = fruits.length - 1; i >= 0; i--) {
    System.out.printf("우리가 좋아하는 과일 %d 위!: %s! \n", i, fruits[i]);
}

 

배열에 있는 fruits는 모두 5개, (0, 1, 2, 3, 4) 

고로 fruits.length == 5 이므로 

상수 4 대신에 fruit.length-1 로 쓰는게 안전하다고. 

 

 

 

 

package IntStream;

import java.util.stream.IntStream;

public class Practice_04 {
	
	public static void main (String[]args) {
		String[] fruits = {"apple", "banana", "cherry", "peach", "blueberry"};
		IntStream.range(0, fruits.length)
		.map(i -> fruits.length -1 -i) 
		.forEach(i-> {
		System.out.printf("3분기 인기과일 순위: 제 %d위! %s\n", i, fruits[i]);
		
		});
				
	}
}

 

 

 

 

여하튼, 

얘가 계속 나올건가봄.

 

해피코딩