Skip to content

람다식&스트림#6

Open
Leekyoohyun wants to merge 3 commits intomainfrom
use-window
Open

람다식&스트림#6
Leekyoohyun wants to merge 3 commits intomainfrom
use-window

Conversation

@Leekyoohyun
Copy link
Owner

Lamda


람다식이란?

함수형 프로그래밍 → 함수를 정의하고 이 함수를 데이터 처리부로 보내 처리하는 기법

자바는 함수형 프로그래밍을 위해 Java8 부터 람다식을 지원.

람다식: (매개변수, ...) -> {처리내용}
new Calculable(){
	@Override
	public void calculate(int x, int y){ 처리내용 }
};

위를 람다식으로 표현

(x,y) -> { 처리내용 };
public void action(Calculable calculable){
	int x = 10;
	int y = 4;
	calculable.calculate(x,y); //데이터 제공 -> 추상메소드 호출
}
action((x,y) -> {
	int result = x+y;
	System.out.println(result);
});

람다식 CODE

package step05_lamda_and_stream.lamda;

public class LamdaEx {
    public static void main(String[] args) {
        action((x,y) -> {
            int result = x+y;
            System.out.println("result: "+result);
        });

        action((x, y)-> {
            int result = x - y;
            System.out.println("result: "+result);
        });
    }

    public static void action(Calculable calculable){
        //데이터
        int x = 10;
        int y = 4;
        //데이터 처리
        calculable.calculate(x, y);
    }
}

매개변수가 없는 람다식

() -> {
	실행문;
	실행문;
}

() -> 실행문
Person person = new Person();

person.action(() -> {
	System.out.println("출근");
	System.out.println("개발");
	System.out.println("퇴근");
});

person.action(() -> System.out.println("잠"));

리턴값 있는 람다식

person.action((x,y) -> {
	double result = x+y;
	return result;
});

person.action((x, y) -> (x+y));

//or
person.action((x, y) -> sum(x,y));

메소드 참조

(left, right) -> Math.max(left, right);
Math :: max;

Stream

스트림이란?

컬렉션 및 배열에서 for문 쓰거나 Iterator 써서 순회했음.

List<String> list = ...;
for(int i=0; i<list.size(); i++){
	String item = list.get(i);
	//item처리 프린트 등등
}

Set<String> set = ...;
Iterator<String> iterator = set.iterator();
while(iterator.hasNext()){
	String item = iterator.next();
	//요소 처리. 프린트 등등
}

❗이제?

Stream<String> stream = list.stream();
stream.forEach(item -> System.out.println(item));
package step05_lamda_and_stream.stream;

import java.util.*;
import java.util.stream.Stream;

public class StreamExample {
    public static void main(String[] args) {
        //Set 컬렉션
        Set<String> set = new HashSet<>();
        set.add("이규현1");
        set.add("이규현2");
        set.add("이규현3");

        //Stream으로 반복처리하기
        Stream<String> stream = set.stream();
        stream.forEach(name -> System.out.println(name));
    }
}

편하다?

장점

  • 내부 반복자라서 처리 속도가 빠르고, 병렬처리에 효율적
  • 람다식으로 다양한 요소 처리 정의 가능
  • 중간 처리와 최종 처리를 수행하도록 파이프 라인 형성 가능

❗병렬처리는 차차 보기로하자

  • 내부반복자
  • 외부반복자

필터링

요소를 걸러내는 중간 처리 기능

distinct() 중복 제거

요소의 중복을 제거

equals() 가 true면 → 동일한 요소로 판단

package step05_lamda_and_stream.stream;

import java.util.*;

public class FilteringExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("이규현");
        list.add("이규현"); //중복
        list.add("김규현2");
        list.add("김규현3");
        list.add("이규현4");
        
        list.stream()
                .distinct()
                .forEach(name -> System.out.println(name));
        System.out.println();
        
        //김으로 시작하는 요소 필터링
        list.stream()
                .filter(name -> name.startsWith("김"))
                .forEach(name -> System.out.println(name));
        System.out.println();

        //중복요소 먼저 제거 후 -> 필터링
        list.stream()
                .distinct()
                .filter(name -> name.startsWith("김"))
                .forEach(name -> System.out.println(name));
    }
}

요소 정렬

compare(x,y)

@Override
public int compareTo(Student o){
	//score와 o.score 비교해서 
	//같으면 0 작으면 음수 크면 양수
	return Integer.compare(score, o.score);
}

sorted()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant