38일차

백엔드를 팝니다·2024년 8월 7일

개발자 수업

목록 보기
27/72

JAVA_람다식

// TODO: 람다식(Ramda) : 자바스크립트 화살표함수 비슷
// 일반 함수(메소드) : 사용법 - 자료형 함수명(매개변수...) {return 실행문;}
// => 위의 함수를 간단하게 사용하기 위해 나타난 표기법
// TODO : 일반함수 => 람다식으로 고치는 방법 :
// 1) 자료형, 함수명 생략한다 2) () {} 사이에 ->(화살표) 추가한다 3) {} 안에 실행문이 1줄이면 중괄호를 생략한다.
// 4) {} 안에 return 예악어가 있으면 중괄호를 생략할 수 없다.
//TODO: 람다식 사용처 : 1) 스트림에서 람다식(표기법) 사용 가능
//2) 익명클래스/익명인터페이스 에서 람다식 (표기법) 사용 가능

// 예제 1) void myPrint(){
// System.out.println("출력");
// }
// => 람다식 : () -> System.out.println("출력");

// 예제 2) void myPrint2(int a) { System.out.println("출력" + a); }
// => 람다식 : (a) ->System.out.println("출력" + a);~~
//예제 3 ) void myPrint3(double b) {System.out.println("출력" + b); }
// => 람다식 : (b) -> System.out.println("출력"+b);

// TODO: 1) 스트림의 동작 방식 :
// 1-1) 대상 : 배열
// 1-2) 자동 반복 : 내부적으로 반복문이 실행되는 구조 (처음 ->끝:자동반복)
// 1-3) 람다식 사용 : (매개변수:배열의값)->{실행문}
// 예) 밑에 예제 적용 : x -> System.out.println(x)
// i=0 일때 : "A" -> System.out.println("A")
// i=1 일때 : "B" -> System.out.println("B")
// ...
// i=4 일때 : "E" -> System.out.println("E")
// 1-4) (옵션) : 옵션을 사용하면 다양한 코딩이 가능함
// => 개선 : 스트림 사용 + 람다식 사용
// => 사용법 : Arrays.stream(변수).forEach((매개변수)->실행문(매개변수))
Arrays.stream(a).forEach(x -> System.out.println(x));

// 간단연습 : 문자열 배열이 아래와 같이 있습니다. 스트림으로 출력하세요
String[] b = { "홍길동", "장길산" };
Arrays.stream(b).forEach(x -> System.out.println(x));

	// 예제 2) ForEach : 실행 또는 출력용
	int[] c = { 1, 2, 3, 4, 5 };
	Arrays.stream(c).forEach(x -> System.out.println(x));

// 간단연습 : 실수 배열이 있습니다. 스트림으로 출력하세요
double[] d = { 1.1, 2.2, 3.3 };

	Arrays.stream(d).forEach(x -> System.out.println(x));

	// TODO: 2) 스트림 고급 사용 : 옵션 적용
	// 예제 3) 정수배열이 아래와 같이 있습니다. 중복을 제거해서 출력하세요
	int[] values = { 1, 1, 1, 2, 2, 2 };

	// 2-1) 옵션 : distinct()
	int[] result = Arrays.stream(values).distinct().toArray();
	Arrays.stream(result).forEach(x -> System.out.println(x));

	// 간단연습 : 실수 배열이 있습니다 중복을 제거해서 새로운 배열을 만들고 forEach로 출력하세요

	double[] values2 = { 1.1, 1.1, 1.1, 2.2, 2.2, 2.2 };
	double[] result2 = Arrays.stream(values2).distinct().toArray();
	Arrays.stream(result2).forEach(x -> System.out.println(x));

	// 예제4 옵션)) skip();
	// 아래 배열에서 첫번째 값은 빼고 모두 출력하세요
	int[] e = { 1, 2, 3, 4, 5 };
	int[] result3 = Arrays.stream(e).skip(1).toArray();
	Arrays.stream(result3).forEach(x -> System.out.println(x));

	// 간단연습 : 실수 배열에서 2개만 제외하고 출력하세요

	double[] f = { 1.1, 2.2, 3.3, 4.4 };
	double[] result4 = Arrays.stream(f).skip(2).toArray();
	Arrays.stream(result4).forEach(x -> System.out.println(x));

	// 예제5) 옵션) limit(개수)
	// 배열에서 첫번째 값은 제외하고 총 3개만 출력하세요
	int[] g = { 1, 2, 3, 4, 5 };

	int[] result5 = Arrays.stream(g).skip(1).limit(3).toArray();
	Arrays.stream(result5).forEach(x -> System.out.println(x));

	// 간단연습 : 실수배열에서 2개 건너뛰고 2개만 출력하세요

	double[] h = { 1.1, 2.2, 3.3, 4.4, 5.5 };
	double[] result6 = Arrays.stream(h).skip(2).limit(2).toArray();
	Arrays.stream(result6).forEach(x -> System.out.println(x));

	// 예제 6 ) 옵션 *) map()
	// 현재 배열에서 각 배열의 값에 1씩 더해서 새로운 배열을 생성해서 출력
	// 결과 : 23456
	int[] i = { 1, 2, 3, 4, 5 };
	int[] result7 = Arrays.stream(i).map(x -> x+1).toArray();
	Arrays.stream(result7).forEach(x -> System.out.println(x));
	

// 간단연습 : 실수 배열에서 1식 빼기해서 새로운 배열을 만들어서 출력하세요
double[] j = {1.1,2.2,3.3,4.4,5.5};
double [] result8=Arrays.stream(j).map(x -> x-1).toArray();
Arrays.stream(result8).forEach(x -> System.out.printf("%.1f", x));

	// 예제7 옵션 *) filter(람다식)
	//복습 : 문자열길이(크기) 가져오기 : 문자열.length()
	String[] k = {"홍12" , "길" , "동1"};

// System.out.println(k[0].length());
String[] result9 = Arrays.stream(k).filter(x -> x.length() > 1).toArray(x -> new String[x]);
Arrays.stream(result9).forEach(x -> System.out.println(x));

// 간단연습 : 문자열 배열이 있습니다. 문자열의 길이 3보다 작은것만 배열을 만들어서 출력하세요
// 문자열의 길이 3보다 작은것만 배열을 만들어서 출력하세요

	  String[] l = {"홍길동" , "장길", "산" , "연개소문"};
	 String [] result10 = Arrays.stream(l).filter(x -> x.length() < 3).toArray(x -> new String[x]);
	 Arrays.stream(result10).forEach(x -> System.out.println(x));

//스트림2 향상된 배열 (List) , 실무

List<String> list = new ArrayList<>();

Collections.addAll(list, "apple", "apple", "ball", "car", "daddy");
System.out.println(list);


// 출력: apple apple ball car daddy
//복습 list.size() - 항상된 배열의 크기(길이, 개수)
//복습 : 조회 - 변수.get(방번호)
for (int i = 0; i < list.size(); i++) {
	System.out.printf(list.get(i) + " ");
}


//출력:forEach()
list.forEach(x -> System.out.println(x + " "));

List<Integer> list2 = new ArrayList<>();
Collections.addAll(list2, 1,2,3,4,5);
System.out.println();
list2.forEach(x -> System.out.printf(x + " "));

System.out.println();

System.out.println();
//예제 2) 옵션 *) map(람다식)
//아래 소문자를 대문자로 고쳐서 출력하세요 :
//힌트 : 문자열.toUpperCase() (대문자 바꾸기)
List list3 = new ArrayList<>();
Collections.addAll(list3, "a","b","c");

System.out.println(list3); // [a, b, c]

List result = list3.stream()
.map(x -> x.toUpperCase()) // 각 배열값 대문자 바꾸기
.collect(Collectors.toList()); // 새로운 향상된 배열 만들기

//출력
result.forEach(x -> System.out.print(x + " ")); // A B C
System.out.println();

//간단연습 : 아래 대문자를 소문자로 고쳐서 출력하세요.

List list4 = new ArrayList<>();
Collections.addAll(list4, "A","B", "C");
List result2 = list4.stream().map(x -> x.toLowerCase()).collect(Collectors.toList());
result2.forEach(x -> System.out.print(x + " "));

//예제3 ) 옵션 distinct() : 중복제거
//아래 향상된 배열에서 중복을 제거해서 출력하세요
List list5 = new ArrayList();
Collections.addAll(list5, 1,1,1,2,2,2);
System.out.println();

// 중복제거
List result3 = list5.stream().distinct().collect(Collectors.toList());
result3.forEach(x -> System.out.print(x + " "));
System.out.println();

// 간단연습 : 실수배열 증복제거 출력

 List<Double> list6 = new ArrayList<Double>();

Collections.addAll(list6, 1.1,1.1,1.1,2.2,2.2,2.2);
List result4 = list6.stream().distinct().collect(Collectors.toList());
result4.forEach(x -> System.out.printf(x + " "));
System.out.println();
// 예제 4) 옵션) skip(개수) : 건너뛰기
List list7 = new ArrayList();
Collections.addAll(list7, 1,2,3,4,5);
List result5 = list7.stream().skip(1).collect(Collectors.toList());
result5.forEach(x -> System.out.print(x+ " "));
System.out.println();
// 예제6 filter(람다식) : 조건식에 해당하는 새로운 배열을 만드는 옵션
//문자열.length()
List list9 = new ArrayList<>();
Collections.addAll(list9, "홍12", "길1", "동");
List result6 = list9.stream().filter(x -> x.length() > 1).collect(Collectors.toList());
result6.forEach(x -> System.out.print(x+ " "));

profile
백엔드 고수가 되고싶은 사람

0개의 댓글