当前位置:网站首页>Functional interface lambda, elegant code development

Functional interface lambda, elegant code development

2022-06-11 05:52:00 Endwas

Welcome to my blog , communication :https://endwas.cn

JDK Now there are many Functional Interface This feature is used to replace our traditional anonymous inner class writing ,
Traditionally we use

  1. Instantiation interface
  2. Rewrite the corresponding method in the interface
    To help us achieve , But the code of this method is miscellaneous , And it doesn't look good .
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
    

            @Override
            public void onClick(View v) {
    
                Toast.makeText(MainActivity.this, "onClick", Toast.LENGTH_SHORT).show();
            }
        });

therefore Java8 Added Functional Interface Functional interface , His characteristic is that there is only one abstract method , This feature helps us when transferring parameters , The compiler will know which method we are implementing , Write according to the corresponding format lambda The expression is OK , Development is easy to understand .

I believe you still don't know what the use is , I can't understand , It doesn't matter. Let's take an example

1. Definition and use

This interface you need to determine ,1. Whether parameters are required , Is a parameter of any type ( Generic ) Or a specific type ;2. Whether to return a value , Whether the return value is of any type or fixed, such as boolean;

  • Defined a Animal Interface , Enter the reference String, Return value void, When we use this method, we should follow this standard
@FunctionalInterface
public interface Animal {
    
    void eat(String food);
}
  • Methods defined lunch, You need to pass in the above Functional Interface As the reference ;
  • stay lunch Inside the method body Anywhere you want Call the eat Abstract method ;
static void lunch(Animal animal) {
    
	System.out.println("animal is eating");
	animal.eat("hao chi!");
	System.out.println("animal have had lunch");
}
  • So we can use lambda Expression to implement the specific interface method ;
  • Follow the abstract method specification : A into the refs , We define this input parameter as message, No return value means no return;
public class main {
    
    public static void main(String[] args) {
    
        lunch(message -> {
    
            message += " Have a big meal ";
            System.out.println(message);
        });
    }

2.JDK Functional interface defined in

1. Runnable class

characteristic : Without the participation , No return value

@FunctionalInterface
public interface Runnable {
    
    void run();
}

Runnable r = ()->{
    
            System.out.println("this is runnable interface");
};
new Thread(r).start();

2. Callable class

characteristic : Without the participation , There is a return value V

@FunctionalInterface
public interface Callable<V> {
    
    V call() throws Exception;
}

 Callable c = ()-> "callable.class";
 Future submit = Executors.newSingleThreadExecutor().submit(c);
 Optional.of(submit).ifPresent(o->{
    
     try {
    
         System.out.println(o.get());
     } catch (InterruptedException e) {
    
         e.printStackTrace();
     } catch (ExecutionException e) {
    
         e.printStackTrace();
     }
 });

3.Function class

characteristic : Ginseng with entry T, There is a return value R

@FunctionalInterface
public interface Function<T, R> {
    
    R apply(T var1);
}

4.Consumer class

characteristic : Ginseng with entry T, No return value

@FunctionalInterface
public interface Consumer<T> {
    
    void accept(T var1);
}

5.Supplier class

characteristic : Without the participation , There is a return value T

@FunctionalInterface
public interface Supplier<T> {
    
    T get();
}

6.Predict class

characteristic : Ginseng with entry T, There is a return value boolean

@FunctionalInterface
public interface Predicate<T> {
    
    boolean test(T var1);
The interface name Input type The output type The core approach explain
Consumer[T]Tvoidaccept(T) Consumer
Supplier[T]voidTT get() Supply type
Function[T,R]TRR apply(T) functional
Predicate[T]Tbooleanboolean test(T) Judgmental

Roughly according to the type, there are these kinds of ,Function There are also some extensions inside the package , such as DoubleConsumer, The input parameter changes from generic to double etc. ;

summary :

Functional Interface Help us start functional programming , In many packages, corresponding use has been added , such as list Of forEach、Stream Bag, etc 、Optional Packages and other internal packages use functional interfaces as methods , Let's call the logic we want inside the method body ;

原网站

版权声明
本文为[Endwas]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020533117806.html