Please Explain Java 8 Method Reference to instance Method using class name

后端 未结 4 1986
栀梦
栀梦 2020-12-03 18:04
public interface MyFunc {

    boolean func(T v1, T v2);

}
public class HighTemp {

    private int hTemp;

    HighTemp(){

           


        
4条回答
  •  感动是毒
    2020-12-03 18:51

    This is the Interface

    package learninglambdaexp;
    
    @FunctionalInterface
    public interface TempInterface {
    
        public boolean validTemp(Temperature temp);
    }
    

    This is the class

    package learninglambdaexp;
    
    public class Temperature {
    
        private int temp;
    
        public Temperature(int temp) {
            this.temp = temp;
        }
    
        public boolean isEvenTemp() {
            return temp % 2 == 0;
        }
    
        public boolean isOddTemp(){
        return !isEvenTemp();
        }
    }
    

    This is the Class with the Main Method

    package learninglambdaexp;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class AnotherMainClass {
    
        public static void main(String[] args) {
    
            List tempCollection = new ArrayList<>();
            tempCollection.add(new Temperature(100));
            tempCollection.add(new Temperature(20));
            tempCollection.add(new Temperature(30));
            tempCollection.add(new Temperature(40));
            tempCollection.add(new Temperature(50));
            tempCollection.add(new Temperature(60));
            tempCollection.add(new Temperature(70));
            int k1 = countVariation(tempCollection, Temperature::isEvenTemp);
            //int k2 = countVariation(Temperature::lowTemp);
            System.out.println(k1);
            // System.out.println(k2); 
        }
    
        private static int countVariation(List tempCollection, TempInterface ti) {
            int count = 0;
            for (Temperature eachTemp : tempCollection) {
                if (ti.validTemp(eachTemp)) { // (eachTemp) -> {return eachTemp.isEvenTemp();};
                    count++;
                }
            }
            return count;
        }
    }
    

    With one argument its easier to understand

提交回复
热议问题