자바 8 의 함수 식 인터페이스 몇 개 를 말 해 보 세 요.

5854 단어 자바
JAVA 8 의 함수 식 인터페이스 Function,Supplier,Predicate,Consumer
이 몇 개의 인 터 페 이 스 는 자바 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;
    }

}

좋은 웹페이지 즐겨찾기