2023.08.14 - 람다, 스트림

mjjin·2023년 8월 13일
0

람다 (Lambda)

람다식
간결한 코드
(전달값1, 전달값2, ...) -> { 코드 }

public void print() {
    String s = "test";
    System.out.println(s);
  }
() -> {
    String s = "test";
    System.out.println(s);
}
---------------------------------"
public void print(String s) {
    System.out.println(s);
}
s -> {System.out.println(s)}
"--------------------------------"
public int add (int x, int y) {
    return x+y;
}
(x,y) -> x+y;
Convertible converter = USD -> System.out.println(USD + "달러 : " + (USD*1400));
converter.convert(3); //3달러 : 4200

// 전달 값이 하나도 없다면?
ConvertibleWithNoParams c1 = () -> System.out.println("1달러 = 1400원");
c1.convert(); //1달러 = 1400원

// 두 줄 이상의 코드가 있다면?
c1 = () -> {
    int USD = 5;
    int KRW = 1400;
    System.out.println(USD * KRW);
};
c1.convert();// 7000

// 전달값이 2개인 경우?
ConvertibleWithTwoParams c2 = (USD, KRW) -> System.out.println(USD * KRW);
c2.convert(4, 1400); // 5600

// 반환값이 있는 경우?
ConvertibleWithReturn c3 = (USD, KRW) -> USD * KRW;
System.out.println(c3.convert(10, 1400)); // 14000

스트림 (Stream)

스트림
많은 데이터에서 내가 원하는 조건에 따라서 필터링을 할 수 있다.
내가 필요한 요소만 꺼내올 수 있다.
컬렉션 프레임, 배열, 파일 등에서 만들어질 수 있다.

//스트림 생성

// Arrays.stream (배열에서 만들기)
int[] scores = {100, 95, 90, 85, 80};
IntStream scoreStream = Arrays.stream(scores);

// 문자열 배열
String[] langs = {"python", "java", "javascript", "c", "c++", "C#"};
Stream<Object> langstream = Arrays.stream(langs);

// Collection.stream() (컬렉션에서 만들기
List<String> langList = new ArrayList<>();
langList = Arrays.asList("python", "java", "javascript", "c", "c++", "C#");
Stream<String> langListStream = langList.stream();

// Stream.of()
Stream<String> langListOfStream = Stream.of("python", "java", "javascript", "c", "c++", "C#");
// 스트림 사용
// 중간 연산 (Intermediate Operation) : filter, map, sorted, distinct, skip, ...
// 최종 연산 (Terminal Operation) : count, min, max, sum, forEach, anyMatch, allMatch, ...
// 스트림은 쓸 때마다 데이터를 소진한다.

int[] scores = {100, 95, 90, 85, 80};
IntStream scoreStream = Arrays.stream(scores);

// 90점 이상인 점수만 출력
Arrays.stream(scores).filter(x -> x >= 90).forEach(x -> System.out.println(x));

// 같은 출력방법 : 클래스명 뒤에 메소드 명을 :(콜론)으로 구분해서 적는다.
Arrays.stream(scores).filter(x -> x >= 90).forEach(System.out::println);
System.out.println("-----------------------------");

// 90 점 이상인 사람의 수
long count = Arrays.stream(scores).filter(x -> x >= 90).count(); // int로 형변환해도 됨
System.out.println(count); // 3
System.out.println("------------------------");

// 90 점 이상인 점수들의 합
int sum = Arrays.stream(scores).filter(x -> x >= 90).sum();
System.out.println(sum); //285
System.out.println("----------------------------");

// 90점 이상인 점수들을 정렬
Arrays.stream(scores).filter(x -> x >= 90).sorted().forEach(System.out::println);
System.out.println("----------------------------");
String[] langs = {"python", "java", "javascript", "c", "c++", "C#"};

//c로 시작하는 프로그래밍 언어
Arrays.stream(langs).filter(x -> x.startsWith("c")).forEach(System.out::println);
System.out.println("--------------------------------");

// java 라는 글자를 포함하는 언어
Arrays.stream(langs).filter(x -> x.contains("java")).forEach(System.out::println);
System.out.println("--------------------------------");
List<String> langList = new ArrayList<>();
langList = Arrays.asList("python", "java", "javascript", "c", "c++", "c#");

// 4글자 이하인 언어를 정렬해서 출력
langList.stream().filter(x -> x.length() <= 4).sorted().forEach(System.out::println);
System.out.println("---------------------------------------");

// 4글자 이하의 언어 중에서 c 라는 글자가 포함된 언어
langList.stream()
        .filter(x -> x.length() <= 4)
        .filter(x -> x.contains("c"))
        .forEach(System.out::println);
System.out.println("--------------------------");

// 4글자 이하의 언어 중에서 c 라는 글자를 포함하는 언어가 있는지?
boolean anyMatch = langList.stream()
        .filter(x -> x.length() <= 4)
        .anyMatch(x -> x.contains("c"));
System.out.println(anyMatch); // true
System.out.println("---------------------------");

// 4글자 이하의 언어들은 모두 c 라는 글자를 포함하는지?
boolean allMatch = langList.stream()
        .filter(x -> x.length() <= 4)
        .allMatch(x -> x.contains("c"));
System.out.println(allMatch); // false
System.out.println("-----------------------");

// 4글자 이하의 언어 중에서 c 라는 글자를 포함하는 언어 뒤에 (어려움) 라는 글자를 출력
// map
langList.stream()
        .filter(x -> x.length() <= 4)
        .filter(x -> x.contains("c"))
        .map(x -> x + "(어려움)")
        .forEach(System.out::println);
System.out.println("-----------------------------");

// c라는 글자를 포함하는 언어를 대문자로 출력
langList.stream()
        .filter(x -> x.contains("c"))
        .map(String::toUpperCase)
        .forEach(System.out::println);
System.out.println("-----------------------------");

// c 라는 글자를 포함하는 언어를 대문자로 변경하여 리스트로 저장
List<String> langListStartsWithC = langList.stream()
        .filter(x -> x.contains("c"))
        .map(String::toUpperCase)
        .collect(Collectors.toList());
langListStartsWithC.stream().forEach(System.out::println);

퀴즈


// 내 풀이
public class _Quiz_10 {
    public static void main(String[] args) {
        Customer[] customers = {
                new Customer("챈들러", 50),
                new Customer("레이첼", 42),
                new Customer("모니카", 21),
                new Customer("벤자민", 18),
                new Customer("제임스", 5)};
        Arrays.stream(customers)
                .map(x -> x.age >= 20 ? x.name + " : 5000원": x.name + " : 무료")
                .forEach(System.out::println);
    }
}

class Customer {
    String name;
    int age;

    public Customer(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
//정답
public class _Quiz_10 {
    public static void main(String[] args) {
        List<Customer> list = new ArrayList<>();
        list.add(new Customer("챈들러", 50));
        list.add(new Customer("레이첼", 42));
        list.add(new Customer("모니카", 21));
        list.add(new Customer("벤자민", 18));
        list.add(new Customer("제임스", 5));


        list.stream()
                .map(x -> x.age >= 20 ? x.name + " : 5000원": x.name + " : 무료")
                .forEach(System.out::println);
    }
}

class Customer {
    String name;
    int age;

    public Customer(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

0개의 댓글