자바

JAVA STEP 47. 함수형 인터페이스

IT의 큰손 2023. 3. 2. 18:55
728x90

★ 표준 API 함수형 인터페이스

  1.  Consumer
    • Consumer<T>
    • BiConsumer<T,U>
  2. Suplier
    • Supplier<T>
  3. Function
    • Function<T,R>
    • BiFunction<T,U,R>
  4. Operator
    • UnaryOperator<T>
    • BinaryOperator<T>
    • Function 하위셋
    • 행동 > 연산자 역할
  5. Predicate
    • Predicate<T> 
    • BiPredicate<T,U>
    • 행동 > 판단 역할
    • Function 하위셋

■ Consumer 예제

  •  매개변수를 받아서 소비하는 업무를 구현하는 인터페이스
  • acceptXXX() 추상 메소드 제공
  • 소스코드
  •  
private static void m1() {
		
		//사용자 정의 함수형 인터페이스
		MyConsumer m1 = num -> System.out.println(num);
		m1.test(100);
		
		//표준 API 함수형 인터페이스(Consumer<T>);
		Consumer<Integer> c1 = new Consumer<Integer>() {
			
			public void accept(Integer num) {
				System.out.println(num);
			}
		};
		c1.accept(20);
		
		Consumer<String> c2 = txt -> System.out.println(txt);
		c2.accept("홍길동");
		
		Consumer<String> c3 = txt -> System.out.println(txt.length());
		c3.accept("홍길동");
		
		Consumer<Integer> c4 = count -> {
			for (int i=0; i<count; i++) {
				System.out.println(i);
			}
			System.out.println();
		};
		c4.accept(10);
		c4.accept(5);
		
		
		
		BiConsumer<String, Integer> bc1 = (name, age) -> {
			System.out.printf("이름 : %s, 나이 : %d세\n", name, age);
		};
		bc1.accept("홍길동", 20);
		
		IntConsumer ic1 = num -> System.out.println(num * num);
		ic1.accept(10);
		
		//Consumer<T>		: 범용
		//BiConsumer<T,U>	: 범용
		//IntConsumer		: int형 전용
		
		//(마음대로 자료형, Int형)
		ObjIntConsumer<String> oic1 = (txt, num) -> {
			
		};
		
		
		
	}
}

 

■ Supplier 예제

  • Supplier<T>
  • getXXX() 추상 메소드 제공 
  • 매개변수 없이 반환값을 돌려주는 업무를 구현하는 인터페이스
  • 소스코드
  •  
private static void m2() {
		
		Supplier<Integer> s1 = () -> {return 100;};
		System.out.println(s1.get());
		
		Supplier<Double> s2 = () -> Math.random();
		System.out.println(s2.get());
		
		Supplier<String> s3 = () -> "홍길동";
		System.out.println(s3.get());
		
		Supplier<Integer> s4 = () -> {
			
			//Calendar : 추상 클래스
			//Calendar now = new Calendar();
			//Calendar now = new GregorianCalendar();
			Calendar now = Calendar.getInstance();
			
			return now.get(Calendar.HOUR_OF_DAY);
		};
		System.out.println(s4.get());
		
		
		
	}

 

■ Function 예제

  • Function<T,R>
  • BiFunction<T,U,R>
  • 매개변수를 전달하면, 처리 후 반환값을 돌려주는 업무를 구현하는 인터페이스
  • applyXXX() 추상 메소드 제공
  • 소스코드
  •  
private static void m3() {		
		
		Function<Integer,Boolean> f1 = num -> num > 0;
		System.out.println(f1.apply(10));
		System.out.println(f1.apply(-10));
		
		Function<String,Integer> f2 = txt -> txt.length();
		System.out.println(f2.apply("홍길동"));
		System.out.println(f2.apply("홍길동입니다"));
		
		User user = new User("1", "홍길동", 20, "M", "서울", "010-1234-5678");
		User user2 = new User("2", "호호호", 20, "F", "서울", "010-1234-5678");
		
		Function<User, String> f3 = u -> u.getGender().equals("M") ? "남자" :"여자";
		System.out.println(f3.apply(user));
		System.out.println(f3.apply(user2));
		
		BiFunction<Integer,Integer,Integer> bf1 = (a,b) -> a+b;
		System.out.println(bf1.apply(10, 20));
		
		BiFunction<Integer,Integer,String> bf2 = (a,b) -> {
		
			if(a>b) {
				return "크다";
			}else if(a<b) {
				return "작다";
			}else {
				return "같다";
			}
		};
		System.out.println(bf2.apply(10, 5));
		System.out.println(bf2.apply(5, 10));
		System.out.println(bf2.apply(10, 10));
		
		
	}

 

■ Operator 예제

  • UnaryOperator<T>
  • BinaryOperator<T>
  • 매개변수를 전달하면, 처리 후 반환값을 돌려주는 업무를 구현하는 인터페이스
  • applyXXX() 추상 메소드 제공
  • 추상 메소드의 매개변수와 반환 값이 자료형이 동일하다.
  • 소스코드
  •  
private static void m4() {
		
		BiFunction<Integer, Integer, Integer> bf1 = (a,b) -> a+b;
		System.out.println(bf1.apply(10, 20));
		
		BinaryOperator<Integer> bo1 = (a,b) -> a+b;
		System.out.println(bo1.apply(10, 20));
		
		Function<Integer, Integer> bf2 = num -> num*num;
		System.out.println(bf2.apply(10));
		
		UnaryOperator<Integer> bo2 = num -> num * num;
		System.out.println(bo2.apply(20));
		
	}

 

■ Predicate 예제

  • Predicate<T>
  • BiPredicate<T,U>
  • 매개변수를 전달하면, 처리 후 반환값을 돌려주는 업무를 구현하는 인터페이스
  • testXXX() 추상 메소드 제공
  • 논리 검사 전용
  • 소스코드
  •  
private static void m5() {
	
		Function<Integer, Boolean> f1 = num -> num >0;
		System.out.println(f1.apply(10));
		System.out.println(f1.apply(-10));
		
		Predicate<Integer> p1 = num -> num > 0;
		System.out.println(p1.test(10));
		System.out.println(p1.test(-10));
		
		BiPredicate<Integer, Integer> p2 = (a,b) -> a > b;
		System.out.println(p2.test(10, 20));
		
	}

 

■ 종합 예제

  • 소스 코드
  •  
private static void m6() {
		
		//함수형 인터페이스 중 일부 > 서로간의 결과를 결합(연결) > 람다식 연산
		User hong = new User("1", "홍길동", 20, "M", "서울", "010-1234-5678");
		
		//업무 1.
		Consumer<User> c1 = user -> System.out.println("이름 : " + user.getName());
		c1.accept(hong);
		
		//업무 2.
		Consumer<User> c2 = user -> System.out.println(("나이 : " + user.getAge()));
		c2.accept(hong);
		System.out.println();
		
		//업무 3. 업무1 + 업무2 동시에 실행 > 기존 c1과 c2를 재사용?
		test(hong, c1, c2); //한번의 행동
		System.out.println();
		
		//c3 = c1+c2;
		Consumer<User> c3 = c1.andThen(c2);
		c3.accept(hong);
		System.out.println();
		
		Consumer<User> c4 = user -> System.out.println("전화 : " + user.getTel());
		
		Consumer<User> c5 = c1.andThen(c2).andThen(c4); //c1+c2+c4
		c5.accept(hong);
		System.out.println();
		
		Consumer<User> c6 = user -> {
			System.out.println("이름 : " + user.getName());
			System.out.println("나이 : " + user.getAge());
		};
		
		System.out.println();
		System.out.println();
		System.out.println();
		
		Function<Integer, Boolean> f1 = num -> num > 0;
		System.out.println(f1.apply(10));
		
		Function<Boolean, String> f2 = result -> result? "성공" : "실패";
		System.out.println(f2.apply(true));
		
		//f1 + f2 = f3
		Function<Integer,String> f3 = f1.andThen(f2);
		System.out.println(f3.apply(10));
		
		Function<String, Integer> f4 = txt -> txt.length();
		
		//f1+f2+f4
		Function<Integer,Integer> f5 = f1.andThen(f2).andThen(f4);
		System.out.println(f5.apply(10));
		
		System.out.println();
		System.out.println();
		System.out.println();
		
		//2의 배수
		Predicate<Integer> p1 = num -> num%2 == 0;
		
		//3의 배수
		Predicate<Integer> p2 = num -> num%3 == 0;
		
		int a = 6;
		
		System.out.println(p1.test(a));
		System.out.println(p2.test(a));
		System.out.println();
		
		//a가 2와 3의 공배수인지?
		System.out.println(p1.test(a) && p2.test(a));
		
		//p1 && p2
		Predicate<Integer> p3 = p1.and(p2);
		System.out.println(p3.test(a));
		
		//p1 || p2
		Predicate<Integer> p4 = p1.or(p2);
		System.out.println(p4.test(a));
		
		//!p1
		Predicate<Integer> p5 = p1.negate();
		System.out.println(p5.test(a));
		
	}
728x90