Behavioral parameterization and lambda expressions-read Java 8 combat

Source: Internet
Author: User
Tags getcolor instance method

0. Overview

The first part: the main characteristics of the behavior parameterization and lambda expression

Part Two: 4~7 the application of flow, including the difference of flow and set, the operation of flow, the parallel execution of collector and note.

Part III: 8~12 How to improve the old code, optional class and Completefuture and the new date and time API with Java8 introduced features

Part IV: 13~16 The main function-type programming

This article is mainly about the first part of the note.

I. Behavior parameterization 1.1 behavior parameterization definition

The behavior parameterization is to take out a block of code and get it ready but not to execute it.

1.2 Example: Requirements

There is a grower who has the following requirements:

    1. Find the Red Apple from the warehouse
    2. Find out all the weights over 150g

Expand:

    1. You might want to find the green apple feature later.
    2. may also need to find more than 200g of weight
1.3 Example: Scenario 1

Traditional implementation Scenarios

Filter Green apple public static list<apple> Filtergreenapples (list<apple> inventory) {list<apple> result = NE    W arraylist<> ();        for (Apple apple:inventory) {if ("green". Equals (Apple.getcolor ())) {Result.add (Apple); }} return result; Can filter any color Apple, the color as a parameter public static list<apple> Filtergreenapplesbycolor (list<apple> inventory, String    color) {list<apple> result = new arraylist<> ();        for (Apple apple:inventory) {if (Apple.getcolor (). Equals (Apple.getcolor ())) {Result.add (Apple); }} return result; Filter different weights of apple public static list<apple> Filtergreenapplesbyweight (list<apple> inventory, int weight) {LIST&L T    apple> result = new arraylist<> ();        for (Apple apple:inventory) {if (Apple.getweight () > Weight) {result.add (Apple); }} return result; Write a method that supports both filtering color and weight public static list<apple> Filtergreenapples (LisT<apple> inventory, String color, int weight, Boolean filtercolorflag) {list<apple> result = N    EW arraylist<> (); for (Apple apple:inventory) {if (Filtercolorflag && apple.getcolor (). Equals (color)) | | (        !filtercolorflag && apple.getweight () > Weight)) {Result.add (Apple); }} return result;
1.4 Example: Scenario 2

Using object passing behavior arguments

Interface Applepredicate {//A function that returns a Boolea value, called the predicate boolean test (Apple Apple); Filter Green public class Applegreencolorpredicate implements Applepredicate {@Override public boolean test (Apple apple)    {return "green". Equals (Apple.getcolor ());         }}//weight greater than 150class Appleheavyweightpredicate implements Applepredicate {@Override public boolean test (Apple apple) {    return Apple.getweight () > 150; }}//red and weighs more than 150class Appleredandheavypredicate implements Applepredicate {@Override public boolean test (Apple Apple    {return "red". Equals (Apple.getcolor ()) && apple.getweight () > 150; }}//implement public static list<apple> Filterapples (list<apple> inventory, applepredicate p) {list<apple>    result = new arraylist<> ();        for (Apple apple:inventory) {if (P.test (apple)) {result.add (Apple); }} return result; public void Test () {list<apple> inventory = new Arraylist<> ();    Filter Green Filterapples (inventory, new Applegreencolorpredicate ());    Weight greater than filterapples (inventory, new Appleheavyweightpredicate ()); Red and weighs more than filterapples (inventory, new Appleredandheavypredicate ());}
1.5 Example: Scenario 3

Passing behavior parameters using anonymous classes

Modeling the selection criteria interface Applepredicate {//A function that returns a Boolea value, called the predicate boolean test (Apple Apple); Implement public static list<apple> Filterapples (list<apple> inventory, applepredicate p) {list<apple> re    Sult = new arraylist<> ();        for (Apple apple:inventory) {if (P.test (apple)) {result.add (Apple); }} return result;    public static void Main (string[] args) {list<apple> inventory = new Arraylist<> ();            Filter Green Filterapples (inventory, new Applepredicate () {@Override public boolean test (Apple apple) {        Return "green". Equals (Apple.getcolor ());    }    });            Weight greater than filterapples (inventory, new Applepredicate () {@Override public boolean test (Apple apple) {        return Apple.getweight () > 150;    }    });             Red and weighs more than filterapples (inventory, new Applepredicate () {@Override public boolean test (Apple apple) { Return "Red". EquaLS (Apple.getcolor ()) && apple.getweight () > 150; }    });}
1.6 Example: Scenario 4

Passing behavior arguments using lambda expressions

interface ApplePredicate {    boolean test(Apple apple);}public static List<Apple> filterApples(List<Apple> inventory, ApplePredicate p) {    List<Apple> result = new ArrayList<>();    for (Apple apple : inventory) {        if (p.test(apple)) {            result.add(apple);        }    }    return result;}public static void main(String[] args) {    List<Apple> inventory = new ArrayList<>();    // 筛选绿色    filterApples(inventory        , (Apple apple) -> "green".equals(apple.getColor()));    // 重量大于150    filterApples(inventory        , (Apple apple) -> apple.getWeight() > 150);    // 红色且重量大于150    filterApples(inventory        , (Apple apple) -> "red".equals(apple.getColor()) && apple.getWeight() > 150);}

Here's a summary:

1.7 Example: Scenario 5

Abstract the list type on the basis of scenario 4

// 定义一个函数式接口interface Predicate<T> {    boolean test(T t);}// 定义一个调用函数式接口的方法public static <T> List<T> filter(List<T> list, Predicate<T> p) {    List<T> result = new ArrayList<>();    for (T e : list) {        if (p.test(e)) {            result.add(e);        }    }    return result;}// 使用public static void main(String[] args) {    List<Apple> inventory = FakeDb.getApples();    List<Apple> redList = Filtering.filter(inventory        , (Apple apple) -> "red".equals(apple.getColor()));    List<String> nonEmptyList = filter(Arrays.asList("1", "", "2")        , (String s) -> !s.isEmpty());}
Second, lambda expression 2.1 lambda expression definition

A way to succinctly represent an anonymous function that can be passed.

    • anonymous {: &.fadein}
    • Function
    • Passed
    • Simple
What does the 2.2 lambda expression look like?

The following is a valid lambda expression of 5

// 1 参数是String s,返回值是int(String s) -> s.length()// 2 参数是Apple a,返回值是boolean(Apple a) -> a.getWeight() > 150//  3 参数是int x,int y 没有返回值 {}内放语句,怎样区分语句与表达式(int x, int y) -> {    System.out.println("Result:");    System.out.println(x + y);}// 4 无参数,返回int() -> 42// 5 参数是两个Apple类型的变量,返回值是boolean(Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight())
2.3 Function-Type interface

A functional interface is an interface that defines only an abstract method .

The signature of an abstract method of a functional interface is basically the signature of a lambda expression, an abstract method called a function descriptor

An annotation: @FunctionalInterface , not required, is used to indicate that the interface is designed as a functional interface

2.4 Use of Lambda

predicate filter out empty strings in the list

// 定义一个函数式接口interface Predicate<T> {    boolean test(T t);}// 定义一个调用函数式接口的方法public static <T> List<T> filter(List<T> list, Predicate<T> p) {    List<T> result = new ArrayList<>();    for (T e : list) {        if (p.test(e)) {            result.add(e);        }    }    return result;}// 使用public static void main(String[] args) {    List<String> nonEmptyList = filter(Arrays.asList("1", "", "2")        , (String s) -> !s.isEmpty());}

Consumer calculates the square of each element in the list and outputs

@FunctionalInterfacepublic interface Consumer<T> {    void accept(T t);}public static <T> void forEach(List<T> list, Consumer<T> c) {    for (T i : list) {        c.accept(i);    }}public static void main(String[] args) {    forEach(Arrays.asList(1, 2, 3, 4), (Integer i) -> System.out.println(i * i));}

function** returns the length of each element in the list

@FunctionalInterfacepublic interface Function<T, R> {    R apply(T t);}public static <T, R> List<R> map(List<T> list, Function<T, R> f) {    List<R> result = new ArrayList<>();    for (T s : list) {        result.add(f.apply(s));    }    return result;}public static void main(String[] args) {    List<Integer> result = map(Arrays.asList("1", "22", "333")        , (String s) -> s.length());}

2.5 type Inference
List<Apple> l = new ArrayList<Apple>();List<Apple> l = new ArrayList<>();// Java编译器根据Lambda出现的上下文来推断Lambda表达式参数的类型Predicate<Apple> p = (Apple a) -> 'red'.equals(a.getColor())Predicate<Apple> p = a -> 'red'.equals(a.getColor())
2.6 Method Reference

Mainly to simplify the code

Method reference, 3 kinds of

    • Method reference String.parseint () to a static method
    • Method reference Str.length () to the instance method
    • Method reference to an External object instance method Globalvar.instancemethod ()
List<String> strList = Arrays.asList("a", "b", "A", "B");strList.sort((s1, s2) -> s1.compareToIgnoreCase(s2));strList.sort(String::compareToIgnoreCase); // 等效的方法引用

Constructor reference

Supplier<Apple> c1 = Apple::new; // 指向Apply()构造函数Apple a1 = c1.get();Function<Integer, Apple> c2 = Apple::new; // 指向Apply(int weight)构造函数Apple a2 = c2.apply(110);BigFunction<String, Integer, Apple> c3 = Apple::new;// 指向Apply(String color, Integer weight)Apple c3 = c3.apply("green", 110);
2.7 Lambda Combat

Sort by Apple's weight

// 行为参数化,下面是通过不同方式传递这个行为的// 1.使用对象public class AppleComparator implements Comparator<Apple> {    public int compare(Apple a1, Apple a2) {        return a1.getWeight().compareTo(a2.getWeight());    }}inventory.sort(new AppleComparator());// 2.使用匿名类inventory.sort(new Comparator<Apple>(){    public int compare(Apple a1, Apple a2) {        return a1.getWeight().compareTo(a2.getWeight());    }});    // 3.使用Lambda表达式inventory.sort((Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight()));// 因为类型推断,可以简化成inventory.sort((a1, a2) -> a1.getWeight().compareTo(a2.getWeight()));// 因为有个java.util.Comparator.comparing静态方法,还可以简化成import static java.util.Comparator.comparing;inventory.sort(comparing((a) -> a.getWeight()));// 4.使用方法引用inventory.sort(comparing(comparing(Apple::getWeight)));
2.8 Composite lambda expression

Comparator compounding

// 逆序,苹果按重量递减排序inventory.sort(comparing(Apple::getWeight).reversed());// 比较器链,先按重量递减排序再按国家排序inverntory.sort(comparing(Apple::getWeight).reversed()               .thenComparing(Apple::getCountry));

predicate Compounding

// negate,and,or// 筛选不是红苹果Predicate<Apple> notRedApple = redApple.negate();// 筛选红苹果且重量大于150   或  绿苹果redApple.and(a -> a.getWeight() > 150).or(a -> "green".equals(a.getColor()));// a.or(b).and(c) <==> (a || b) && c

function compounding

// andThen,composeFunction<Integer, Integer> f = x -> x + 1;Function<Integer, Integer> g = x -> x * 2;// g(f(x))Function<Integer, Integer> h = f.andThen(g);int result = h.apply(1);// f(g(x))Function<Integer, Integer> h = f.compose(g);int result = h.apply(1);
Third, the Code

Https://gitee.com/yysue/tutorials-java/tree/master/java-8

Behavioral parameterization and lambda expressions-read Java 8 combat

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.