Lambdalambda expressions using

Keywords: Java Lambda

Lambda (II) lambda expression using

Lambda expression composition:

    param list   arrow        lambda body
    (o1,o2)       ->       o1.getColor().CompareTo(o2.getColor());

Lambda expressions need to have predefined functional interfaces that match them:

Functional interface: predict < T > 
Methods: Boolean test (t t t);

Functional interface: consumption < T > 
Methods: void accept (t t t);

Functional interface: function < T, R > 
Methods: R apply (t t t);

Functional interface: supplier < T > 
Method: T get();

Simple use case, source code is as follows

Consumer<String> c = s -> System.out.println(s);

Function<String,Integer> lambda =  s->s.length();

Predicate<Apple> predicate = a->a.getColor().equals("green");

Function<Apple,Boolean> function = a->a.getColor().equals("red");

Supplier<Apple> instance = Apple::new;

If you want to sort Apple's list now (regular vsLambda):

//implement item1
list.sort(new Comparator<Apple>() {
            public int compare(Apple o1, Apple o2) {
                return o1.getColor().compareTo(o2.getColor());

//implement item2
list.sort((o1, o2) -> o1.getColor().compareTo(o2.getColor()));

//implement item2

Custom use, source code is as follows

public static List<Apple> filter(List<Apple> apples, Predicate<Apple> predicate){
        List<Apple> result = new ArrayList<>();
        for(Apple a:apples){
        return result;

public static void main(String[] args) {
        List<Apple> apples = Arrays.asList(new Apple("green", 120), new Apple("red", 150));
        List<Apple> green = filter(apples, a -> a.getColor().equals("green"));
There are at most two input parameters in the java 8 API. If there are multiple parameters, you can define them yourself. The source code is as follows
//custom FunctionalInterface Interface
public interface ThreeFunction<T,U,K,R> {
    R apply(T t,U u,K k);
//Specific use
ThreeFunction<String,Long,String,ComplexApple> tf = ComplexApple::new;
ComplexApple cp = tf.apply("yellow", 111L, "fushi");
Method reference:
 * Conditions derived from the method of use:
 *      1,Instance method of class
 *      2,Object instance method
 *      3,Constructor
public static <T> void useConsume(Consumer<T> consumer,T t){

List<Apple> apples = Arrays.asList(new Apple("red", 100),
                new Apple("green", 150),
                new Apple("abc", 110));;
int i = Integer.parseInt("123");

Function<String,Integer> f = Integer::parseInt;
Integer apply = f.apply("123");

BiFunction<String, Integer, Character> f1 = String::charAt;
Character r1 = f1.apply("hello", 2);

String s = new String("hello");
Function<Integer, Character> f2 = s::charAt;
Character r2 = f2.apply(1);

Supplier<Apple> appleSupplier = Apple::new;
Apple apple = appleSupplier.get();

BiFunction<String,Long,Apple> appleBiFunction = Apple::new;
Apple blue = appleBiFunction.apply("blue", 123L);

Posted by php_guest on Mon, 04 Nov 2019 11:20:34 -0800