본문 바로가기

인강 보습 (인프런,유데미,패스트캠퍼스)/나도코딩의 자바 기본편

익명 클래스, 람다와 스트림 - (2) 함수형 인터페이스, 스트림

함수형 인터페이스 (전반전) 

_04_FunctionalInterface

public class _04_FunctionalInterface {
    public static void main(String[] args) {
        KRWConverter converter = new KRWConverter();
        // converter.convert(2);

        // convertUSD((USD) -> System.out.println(USD + " 달러 = " + (USD * 1400) + " 원"), 1);

        Convertible convertible = (USD) -> System.out.println(USD + " 달러 = " + (USD * 1400) + " 원");
        convertUSD(convertible, 2);

Convertible (Interface) 

package chap_10.converter;

@FunctionalInterface
public interface Convertible {
    void convert(int USD);
}

        *함수형 인터페이스에 추상 메소드가 1개여야 한다 (2개 이상이면 어떤 메소드와 연결되는지 알 수 없어서 에러 발생)

 

KRWConverter (Class) 

package chap_10.converter;

public class KRWConverter implements Convertible {
    @Override
    public void convert(int USD) {
        // 1 달러 = 1400 원
        System.out.println(USD + " 달러 = " + (USD * 1400) + " 원");
    }
}

 

 

 

함수형 인터페이스 (후반전) 

 

_04_FunctionalInterface

package chap_10;

import chap_10.converter.*;

public class _04_FunctionalInterface {
    public static void main(String[] args) {
        KRWConverter converter = new KRWConverter();
        // converter.convert(2);

        // convertUSD((USD) -> System.out.println(USD + " 달러 = " + (USD * 1400) + " 원"), 1);

        Convertible convertible = (USD) -> System.out.println(USD + " 달러 = " + (USD * 1400) + " 원");
        convertUSD(convertible, 2);

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

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

        // 전달값이 2개인 경우?
        ConvertibleWithTwoParams c2 = (d, w) -> System.out.println(d + " 달러 = " + (d * w) + " 원");
        c2.convert(10, 1400);

        // 반환값이 있는 경우?
        ConvertibleWithReturn c3 = (d, w) -> d * w;
        int result = c3.convert(20, 1400);
        System.out.println("20 달러 = " + result + " 원");
    }

    public static void convertUSD(Convertible converter, int USD) {
        converter.convert(USD);
    }
}

        *인터페이스 ConvertibleWithNoParams, ConvertibleWithReturn, ConvertibleWithTwoParams 생성

 

스트림 - (1) 

public class _05_Stream {
    public static void main(String[] args) {
        // 스트림 생성

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

        String[] langs = {"python", "java", "javascript", "c", "c++", "c#"};
        Stream<String> langStream = Arrays.stream(langs);

        // Collection.stream()
        List<String> langList = new ArrayList<>();
        // langList.add("python");
        // langList.add("java");
        langList = Arrays.asList("python", "java", "javascript", "c", "c++", "c#");
        // System.out.println(langList.size());
        Stream<String> langListStream = langList.stream();

        // Stream.of()
        Stream<String> langListOfStream = Stream.of("python", "java", "javascript", "c", "c++", "c#");

 

 

스트림 - (2) 

// 스트림 사용
// 중간 연산 (Intermediate Operation) : filter, map, sorted, distinct, skip , ...
// 최종 연산 (Terminal Operation) : count, min, max, sum, forEach, anyMatch, allMatch, ...

// 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 점 이상인 사람의 수
int count = (int) Arrays.stream(scores).filter(x -> x >= 90).count();
System.out.println(count);
System.out.println("----------------------------");

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

 

 

스트림 - (3) 

// "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("----------------------------");

// 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);
System.out.println("----------------------------");

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

 

스트림 - (4) 

 

// 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);