자바 의 함수 식 인터페이스 @ Functional 인터페이스 상세 설명 (소스 코드 첨부)
함수 식 인터페이스의 정의
자바 8 에서 아래 의 임의의 조건 을 만족 시 키 는 인 터 페 이 스 는 모두 함수 식 인터페이스 입 니 다. 1. @ FunctionalInterface 에 의 해 주석 되 는 인터페이스 로 @ FunctionalInterface 주석 에 대한 제약 을 만족 시 킵 니 다.2. @ FunctionalInterface 에 주석 이 달 린 인터페이스 가 없 지만 @ FunctionalInterface 주석 에 대한 제약 을 만족 시 킵 니 다 @ FunctionalInterface 주석 에 대한 제약: 1. 인터페이스 가 있 고 추상 적 인 방법 만 있 을 수 있 습 니 다. 방법 만 정의 할 수 있 습 니 다. 방법 체 2. 인터페이스 에 Object 류 중의 Public 방법 을 복사 하 는 것 은 함수 식 인터페이스 방법 이 아 닙 니 다.
예 를 들 면:
@FunctionalInterface
interface FunctionalInterfaceTest {
String getInfo(String input);
}
함수 식 인터페이스의 실례
public class Main {
public static void main(String[] args)
throws ClassNotFoundException,
IllegalAccessException,
InstantiationException,
NoSuchMethodException,
InvocationTargetException, NoSuchFieldException {
/**
* 1、lambda
* ,lambda , String , String 。
* FunctionInterfaceTest
*/
FunctionalInterfaceTest fiTest1 = str -> str + " copy";
/**
* 2、Main functionalInterfaceTestMethod , 。
* FunctionInterfaceTest 。
* ( String , String ),
* 。 , java
* 。 , , 。
*/
FunctionalInterfaceTest fiTest2 = Main::functionalInterfaceTestMethod;
/**
* 3、
* : , 。 。
* “ ” “ ” FunctionInterfaceTest ,
* FunctionInterfaceTest , ,String
* new String(str) , 。
* ,JDK , String 。
* String::new, ,
*/
FunctionalInterfaceTest fiTest3 = String::new;
System.out.println(useFunctionalInterface("Hello World!", fiTest1));
System.out.println(useFunctionalInterface("Hello World!", fiTest2));
System.out.println(useFunctionalInterface("Hello World!", fiTest3));
System.out.println(useFunctionalInterface("Hello World!", str -> str + " created by lambda in the context"));
/**
:
Hello World! copy
Hello World! copy 2 by reference
Hello World!
Hello World! created by lambda in the context
*/
}
public static String functionalInterfaceTestMethod(String str) {
return str + " copy 2 by reference";
}
public static String useFunctionalInterface(String str, FunctionalInterfaceTest fiT) {
return fiT.getInfo(str);
}
}
상용 봉 인 된 함수 식 인터페이스
각각 Function, Cosumer, Predicate, Supplier
/**
* , 。 。
Function
T , R
Consumer
T ,
Predicate
T , boolean
Supplier
, T
*/
Function add_postfix = str -> str + "postfix";
Consumer print_string = System.out::println;
Predicate judge_positive = n -> n > 0;
Supplier supplier = () -> "supply";
List list = Arrays.asList("adfsg", "sdafef", "", "s", "231243", "hgjrepjrg");
list.stream()
.map(str -> str + "1")
.filter(str -> str.length() > 2)
.sorted((str1, str2) -> str2.compareTo(str1))
.forEach(System.out::println);
/**
:
sdafef1
hgjrepjrg1
adfsg1
2312431
1234dfgh
*/
이 밖 에 다 중 인자 의 경우 자바 가 BiFunction, BiConsumer, BiPredicate 를 봉인 했다.
// java , BiSupplier
BiFunction combine_string = (str1, str2) -> str1 + str2;
BiConsumer print_two_string = (str1, str2) -> System.out.println(str1 + str2);
BiPredicate str_equal = String::equals;
int bif_result = biFunctionTestMethod("abs", "pdf", (str1, str2) -> str1.length() + str2.length());
biConsumerTestMethod("1234", "dfgh", (str1, str2) -> System.out.println(str1 + str2));
boolean bip_result_1 = biPredictTestMethod("abc", "abc", str_equal),
bip_result_2 = biPredictTestMethod("abc", "def", str_equal);
System.out.println(bif_result);
System.out.println(bip_result_1);
System.out.println(bip_result_2);
/*
:
6
true
false
*/
그 밖 에 compose 와 andThen 방법 도 있 습 니 다. 그 본질은 수학 에서 함수 에 부합 되 는 것 입 니 다. 유일한 차이 점 은 함수 \ (f (x), g (x) \), compose 등 가 는 \ (f (g (x) \), andThen 등 가 는 \ (g (f (x) \) 와 같 습 니 다. 실행 순서 가 다 를 뿐 입 니 다.
// compose andThen
Function compose_function = ((Function) (str -> str + "abc")).compose((Function) (str -> str + str.length()));
System.out.println("Compose function: " + compose_function.apply("Hello World! "));
Function andThen_function = ((Function) (str -> str + "abc")).andThen((Function) (str -> str + str.length()));
System.out.println("AndThen function: " + andThen_function.apply("Hello World! "));
// Bicosumer, cosumer, bifunction
// BiPredicate, Predicate and, or, negate
System.out.println(str_equal.negate().test("a", "a")); // false
System.out.println(judge_positive.and(n -> n > 2).test(5)); // true
System.out.println(judge_positive.or(n -> n < -1).test(-10)); // true
소스 코드
Function.java
/**
* Represents a function that accepts one argument and produces a result.
*
* This is a functional interface
* whose functional method is {@link #apply(Object)}.
*
* @param the type of the input to the function
* @param the type of the result of the function
*
* @since 1.8
*/
@FunctionalInterface
public interface Function {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param the type of input to the {@code before} function, and to the
* composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*
* @see #andThen(Function)
*/
default Function compose(Function super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
*
* @see #compose(Function)
*/
default Function andThen(Function super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
/**
* Returns a function that always returns its input argument.
*
* @param the type of the input and output objects to the function
* @return a function that always returns its input argument
*/
static Function identity() {
return t -> t;
}
}
Consumer.java
/**
* Represents an operation that accepts a single input argument and returns no
* result. Unlike most other functional interfaces, {@code Consumer} is expected
* to operate via side-effects.
*
* This is a functional interface
* whose functional method is {@link #accept(Object)}.
*
* @param the type of the input to the operation
*
* @since 1.8
*/
@FunctionalInterface
public interface Consumer {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
/**
* Returns a composed {@code Consumer} that performs, in sequence, this
* operation followed by the {@code after} operation. If performing either
* operation throws an exception, it is relayed to the caller of the
* composed operation. If performing this operation throws an exception,
* the {@code after} operation will not be performed.
*
* @param after the operation to perform after this operation
* @return a composed {@code Consumer} that performs in sequence this
* operation followed by the {@code after} operation
* @throws NullPointerException if {@code after} is null
*/
default Consumer andThen(Consumer super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}
Predicate.java
/**
* Represents a predicate (boolean-valued function) of one argument.
*
* This is a functional interface
* whose functional method is {@link #test(Object)}.
*
* @param the type of the input to the predicate
*
* @since 1.8
*/
@FunctionalInterface
public interface Predicate {
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T t);
/**
* Returns a composed predicate that represents a short-circuiting logical
* AND of this predicate and another. When evaluating the composed
* predicate, if this predicate is {@code false}, then the {@code other}
* predicate is not evaluated.
*
*
Any exceptions thrown during evaluation of either predicate are relayed
* to the caller; if evaluation of this predicate throws an exception, the
* {@code other} predicate will not be evaluated.
*
* @param other a predicate that will be logically-ANDed with this
* predicate
* @return a composed predicate that represents the short-circuiting logical
* AND of this predicate and the {@code other} predicate
* @throws NullPointerException if other is null
*/
default Predicate and(Predicate super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
/**
* Returns a predicate that represents the logical negation of this
* predicate.
*
* @return a predicate that represents the logical negation of this
* predicate
*/
default Predicate negate() {
return (t) -> !test(t);
}
/**
* Returns a composed predicate that represents a short-circuiting logical
* OR of this predicate and another. When evaluating the composed
* predicate, if this predicate is {@code true}, then the {@code other}
* predicate is not evaluated.
*
*
Any exceptions thrown during evaluation of either predicate are relayed
* to the caller; if evaluation of this predicate throws an exception, the
* {@code other} predicate will not be evaluated.
*
* @param other a predicate that will be logically-ORed with this
* predicate
* @return a composed predicate that represents the short-circuiting logical
* OR of this predicate and the {@code other} predicate
* @throws NullPointerException if other is null
*/
default Predicate or(Predicate super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
/**
* Returns a predicate that tests if two arguments are equal according
* to {@link Objects#equals(Object, Object)}.
*
* @param the type of arguments to the predicate
* @param targetRef the object reference with which to compare for equality,
* which may be {@code null}
* @return a predicate that tests if two arguments are equal according
* to {@link Objects#equals(Object, Object)}
*/
static Predicate isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
/**
* Returns a predicate that is the negation of the supplied predicate.
* This is accomplished by returning result of the calling
* {@code target.negate()}.
*
* @param the type of arguments to the specified predicate
* @param target predicate to negate
*
* @return a predicate that negates the results of the supplied
* predicate
*
* @throws NullPointerException if target is null
*
* @since 11
*/
@SuppressWarnings("unchecked")
static Predicate not(Predicate super T> target) {
Objects.requireNonNull(target);
return (Predicate)target.negate();
}
}
Supplier.java
/**
* Represents a supplier of results.
*
* There is no requirement that a new or distinct result be returned each
* time the supplier is invoked.
*
*
This is a functional interface
* whose functional method is {@link #get()}.
*
* @param the type of results supplied by this supplier
*
* @since 1.8
*/
@FunctionalInterface
public interface Supplier {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.