자바 8 의 함수 식 인터페이스 몇 개 를 말 해 보 세 요.
5854 단어 자바
이 몇 개의 인 터 페 이 스 는 자바 8 에서 이미 정의 되 었 습 니 다.모든 인 터 페 이 스 는 기본적으로 하나의 인터페이스 방법 이 있 기 때문에 사실은 자신 이@Functional Interface 를 통 해 스스로 정의 하여 사용 할 수 있 습 니 다.그러나 사람들 은 당신 에 게 정 의 를 내 렸 습 니 다.그리고 보통 자바 8 이러한 인터페이스 에는 주요 인터페이스 방법 외 에 몇 가지 default 방법 이 있 습 니 다.그래서 우리 가 직접 쓰 는 게 더 편 할 때 가 많아 요.
Predicate 인터페이스(특정 조건 만족 판단,test 방법)
public class AppleFilter {
public static List filterApples(List inventory, Predicate p) {
List result = new ArrayList<>();
for(Apple apple : inventory) {
if(p.test(apple)) {
result.add(apple);
}
}
return result;
}
public static void main(String[] args) {
List inventory = new ArrayList<>();
// ...
inventory.add(new Apple(120, "green"));
inventory.add(new Apple(90, "red"));
filterApples(inventory, Apple::isGreenApple);
filterApples(inventory, Apple::isHeavyApple);
}
@Data
@AllArgsConstructor
@NoArgsConstructor
private static class Apple {
int weight;
String color;
public static boolean isGreenApple(Apple apple) {
return "green".equals(apple.getColor());
}
public static boolean isHeavyApple(Apple apple) {
return apple.getWeight()>100;
}
}
} Consumer 인터페이스(매개 변수 대상 에 대한 일부 조작,accept 방법)
public class LamdaLearn {
// consumer
public static void forEach(List list, Consumer c) {
for(T i : list){
c.accept(i);
}
}
public static void main(String[] args) {
// consumer
forEach(Arrays.asList(1,2,3,4), (Integer i) -> System.out.println(i));
}
} Function 인터페이스(전 송 된 대상 을 비 추고 일반적인 대상 을 되 돌려 줍 니 다.apply 방법)
public class Test {
public static void main(String[] args) throws InterruptedException {
String name = "";
String name1 = "12345";
System.out.println(validInput(name, inputStr -> inputStr.isEmpty() ? " ":inputStr));
System.out.println(validInput(name1, inputStr -> inputStr.length() > 3 ? " ":inputStr));
}
public static String validInput(String name,Function function) {
return function.apply(name);
}
} 공급 업 체 인터페이스(공급 작업,get 방법)
public class LamdaLearn {
public static void main(String[] args) {
//
Supplier filterSupplier = AppleFilter::new;
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.