Java函数式编程整理

Java函数式编程的第一个做用是能够将匿名类改写成函数式表达式,由系统自动判断类型编程

咱们先定义一个接口app

public interface Goods {
    boolean test(int i);
}

传统的匿名类写法ide

public class Anonymous {
    public static void main(String[] args) {
        List<Goods> goodsList = new ArrayList<>();
        goodsList.add(new Goods(){
            @Override
            public boolean test(int i) {
                return 5 - i > 0;
            }
        });
        System.out.println(goodsList.get(0).test(3));
    }
}

运行结果:函数式编程

true函数

使用lamdba表示式的写法工具

public class AnonymousLambda {
    public static void main(String[] args) {
        List<Goods> goodsList = new ArrayList<>();
        goodsList.add(i -> 5 - i > 0);
        System.out.println(goodsList.get(0).test(3));
    }
}

运行结果ui

truethis

像这种一个接口里面只有一个方法的接口,咱们能够称之为函数接口,JDK中有不少这样的接口,固然咱们能够在该接口上打上@FunctionalInterface以代表该接口是一个函数接口spa

@FunctionalInterface
public interface Goods {
    boolean test(int i);
}

咱们先来看一下JDK中的Predicate接口,这是一个能够进行条件判断的接口code

咱们先用传统方式来看一下这么几个条件

  • 判断传入的字符串的长度是否大于5
  • 判断传入的参数是不是偶数
  • 判断数字是否大于10
public class PredicateOne {
    /**
     * 判断长度大于5
     * @param judgeString
     * @return
     */
    public boolean judgeStringLength(String judgeString) {
        return judgeString.length() > 5;
    }

    /**
     * 判断是不是偶数
     * @param judgeInteger
     * @return
     */
    public boolean judgeIntegerOdds(int judgeInteger) {
        return (judgeInteger & 1) == 0;
    }

    /**
     * 判断数字是否大于10
     * @param num
     * @return
     */
    public boolean judgeSecialNumber(int num) {
        return num > 10;
    }

    public static void main(String[] args) {
        PredicateOne predicateOne = new PredicateOne();
        System.out.println(predicateOne.judgeStringLength("12345"));
        System.out.println(predicateOne.judgeIntegerOdds(12345));
        System.out.println(predicateOne.judgeSecialNumber(12345));
    }
}

运行结果

false
false
true

如今改为函数式编程以下

public class PredicateTwo<T> {
    public boolean judgeConditionByFunction(T t, Predicate<T> predicate) {
        return predicate.test(t);
    }

    public static void main(String[] args) {
        PredicateTwo<Integer> integerPredicateTwo = new PredicateTwo<>();
        System.out.println(integerPredicateTwo.judgeConditionByFunction(12345,t -> String.valueOf(t).length() > 5));
        System.out.println(integerPredicateTwo.judgeConditionByFunction(12345,t -> (t & 1) == 0));
        System.out.println(integerPredicateTwo.judgeConditionByFunction(12345,t -> t > 10));
    }

运行结果

false
false
true

咱们知道逻辑判断中有与、或、非的比较,Predicate接口一样具备这样的功能,咱们来看一下它的源码

@FunctionalInterface
public interface Predicate<T> {

    /**
     * 须要实现的比较方法
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);

    /**
     * 逻辑与,相似于&&
     *
     * @param other a predicate that will be logically-ANDed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * AND of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    /**
     * 逻辑非,相似于!
     *
     * @return a predicate that represents the logical negation of this
     * predicate
     */
    default Predicate<T> negate() {
        return (t) -> !test(t);
    }

    /**
     * 逻辑或,相似于||
     *
     * @param other a predicate that will be logically-ORed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * OR of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    /**
     * 逻辑等,相似于equals()方法
     *
     * @param <T> the type of arguments to the predicate
     * @param targetRef the object reference with which to compare for equality,
     *               which may be {@code null}
     * @return a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}
     */
    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }
}

如今咱们加上条件的交集判断

public class PredicateThree<T> {
    /**
     * 两个条件的与操做
     * @param t
     * @param predicate
     * @param predicate1
     * @return
     */
    public boolean judgeConditionByFunctionAnd(T t, Predicate<T> predicate,Predicate<T> predicate1) {
        return predicate.and(predicate1).test(t);
    }

    /**
     * 两个条件的或操做
     * @param t
     * @param predicate
     * @param predicate1
     * @return
     */
    public boolean judgeConditionByFunctionOr(T t, Predicate<T> predicate,Predicate<T> predicate1) {
        return predicate.or(predicate1).test(t);
    }

    /**
     * 对一个条件进行取反
     * @param t
     * @param predicate
     * @return
     */
    public boolean judgeConditionByFunctionNegate(T t,Predicate<T> predicate) {
        return predicate.negate().test(t);
    }

    /**
     * 判断两个对象的值是否相等
     * @param t1
     * @param t2
     * @return
     */
    public boolean judgeConditionIsEquals(T t1,T t2) {
        return Predicate.isEqual(t1).test(t2);
    }

    public static void main(String[] args) {
        PredicateThree<Integer> integerPredicateThree = new PredicateThree<>();
        System.out.println(integerPredicateThree.judgeConditionByFunctionAnd(12345,t -> t > 10,t ->(t & 1) == 0));
        System.out.println(integerPredicateThree.judgeConditionByFunctionOr(12345,t -> t > 10,t ->(t & 1) == 0));
        System.out.println(integerPredicateThree.judgeConditionByFunctionNegate(12345,t -> t > 10));
        System.out.println(integerPredicateThree.judgeConditionIsEquals(123,123));
    }
}

运行结果

false
true
false
true

咱们再来看一下JDK中的Consumer接口,Consumer的做用是 给定义一个参数,对其进行(消费)处理,处理的方式能够是任意操做.

咱们来获取一群人中名字为lisa的全部人,传统方式以下

@Data
@AllArgsConstructor
public class Person {
    private String name;
    private int age;
}
public class ConsumerOne {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        Consumer<Person> consumer = new Consumer<Person>() {
            @Override
            public void accept(Person person) {
                if (person.getName().equals("lisa")) {
                    personList.add(person);
                }
            }
        };
        List<Person> list = Arrays.asList(
                new Person("lisa", 23),
                new Person("Mike", 33),
                new Person("lisa", 27),
                new Person("Jack", 25)
        );
        for (Person person : list) {
            consumer.accept(person);
        }
        System.out.println(JSON.toJSONString(personList));
    }

}

运行结果

[{"age":23,"name":"lisa"},{"age":27,"name":"lisa"}]

改写成函数式编程以下

public class ConsumerTwo {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        Consumer<Person> consumer = t -> {
            if (t.getName().equals("lisa")) {
                personList.add(t);
            }
        };
        Arrays.asList(
                new Person("lisa", 23),
                new Person("Mike", 33),
                new Person("lisa", 27),
                new Person("Jack", 25)
        ).stream().forEach(consumer);
        System.out.println(JSON.toJSONString(personList));
    }
}

运行结果

[{"age":23,"name":"lisa"},{"age":27,"name":"lisa"}]

stream后面会全面讲解,咱们来看一下Consumer接口的源码

@FunctionalInterface
public interface Consumer<T> {

    /**
     * 给指定的参数t执行定义的操做
     *
     * @param t the input argument
     */
    void accept(T t);

    /**
     *  对给定的参数t执行定义的操做执行再继续执行after定义的操做 
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code Consumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

如今咱们只须要大于25岁的lisa

public class ConsumerThree {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        Consumer<Person> consumer = t -> {
            if (t.getName().equals("lisa")) {
                personList.add(t);
            }
        };
        consumer = consumer.andThen(t -> personList.removeIf(x -> x.getAge() < 25));
        Arrays.asList(
                new Person("lisa", 23),
                new Person("Mike", 33),
                new Person("lisa", 27),
                new Person("Jack", 25)
        ).stream().forEach(consumer);
        System.out.println(JSON.toJSONString(personList));
    }
}

运行结果

[{"age":27,"name":"lisa"}]

这里removeIf()的参数是一个Predicate接口,它的源码以下,它是在Collection接口源码中

default boolean removeIf(Predicate<? super E> filter) {
    Objects.requireNonNull(filter);
    boolean removed = false;
    final Iterator<E> each = iterator();
    while (each.hasNext()) {
        if (filter.test(each.next())) {
            each.remove();
            removed = true;
        }
    }
    return removed;
}

咱们再来看一下JDK中的Function接口,Function的做用是将一个给定的对象进行加工,而后返回加工后的对象,这个加工能够是任何操做.

传统方式以下

@Data
@AllArgsConstructor
@ToString
public class Person {
    private String name;
    private int age;
}
@AllArgsConstructor
@Data
@ToString
public class Result {
    private String msg;
    private String code;
    private Person person;
}
public class FunctionOne {
    public static void main(String[] args) {
        Function<Person,Result> function = new Function<Person, Result>() {
            @Override
            public Result apply(Person person) {
                return new Result("成功","200",person);
            }
        };
        System.out.println(function.apply(new Person("lisa",24)));
    }
}

运行结果

Result(msg=成功, code=200, person=Person(name=lisa, age=24))

改写成函数式编程以下

public class FunctionTwo {
    public static void main(String[] args) {
        Function<Person,Result> function = x -> new Result("成功","200",x);
        System.out.println(function.apply(new Person("lisa",24)));
    }
}

运行结果

Result(msg=成功, code=200, person=Person(name=lisa, age=24))

Function接口的源码以下

@FunctionalInterface
public interface Function<T, R> {

    /**
     *  将一个给定的对象进行加工,而后返回加工后的对象,能够将该方法理解为一个一维函数,参数R是自变量,参数T是因变量. 
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);

    /**
     *  组合函数,在调用当前function以前执行 
     *
     * @param <V> the type of input to the {@code before} function, and to the
     *           composed function
     * @param before the function to apply before this function is applied
     * @return a composed function that first applies the {@code before}
     * function and then applies this function
     * @throws NullPointerException if before is null
     *
     * @see #andThen(Function)
     */
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

    /**
     *  组合函数,在调用当前function以后执行 
     *
     * @param <V> the type of output of the {@code after} function, and of the
     *           composed function
     * @param after the function to apply after this function is applied
     * @return a composed function that first applies this function and then
     * applies the {@code after} function
     * @throws NullPointerException if after is null
     *
     * @see #compose(Function)
     */
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }

    /**
     *  原函数,返回与参数一致的函数,便可以理解为 y = x 
     *
     * @param <T> the type of the input and output objects to the function
     * @return a function that always returns its input argument
     */
    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

----------------------------------------------------------------------------------

而另外一个最主要的做用就是对集合的操做,从传统编程到函数式编程(lambda),咱们先来看一个最简单的例子

@Data
@AllArgsConstructor
public class Artist {
    private String name;
    private String homeTown;

    public boolean isFrom(String homeTown) {
        if (this.homeTown.equals(homeTown)) {
            return true;
        }
        return false;
    }
}

这是一个艺术家的简单类,包含名字和家乡。

如今咱们来建立一个艺术家的集合,而后断定来自伦敦的艺术家有多少人

public class ComeFrom {
    public static void main(String[] args) {
        List<Artist> artists = new ArrayList<>();
        artists.add(new Artist("Martin","London"));
        artists.add(new Artist("Shirly","Beijing"));
        artists.add(new Artist("Dilon","London"));
        artists.add(new Artist("Dave","NewYork"));
        int count = 0;
        for (Artist artist : artists) {
            if (artist.isFrom("London")) {
                count++;
            }
        }
        System.out.println(count);
    }
}

运行结果:

2

如今咱们来改形成函数式的编程

public class ComeFromStream {
    public static void main(String[] args) {
        List<Artist> artists = new ArrayList<>();
        artists.add(new Artist("Martin","London"));
        artists.add(new Artist("Shirly","Beijing"));
        artists.add(new Artist("Dilon","London"));
        artists.add(new Artist("Dave","NewYork"));
        long count = artists.stream().filter(artist -> artist.isFrom("London"))
                .count();
        System.out.println(count);
    }
}

运行结果

2

这里第一种方式,咱们称为外部迭代;而第二种方式,咱们称为内部迭代,而stream是这种用函数式编程方式在集合类上进行复杂操做的工具。

若是咱们对代码稍做修改

public class ComeFromStream {
    public static void main(String[] args) {
        List<Artist> artists = new ArrayList<>();
        artists.add(new Artist("Martin","London"));
        artists.add(new Artist("Shirly","Beijing"));
        artists.add(new Artist("Dilon","London"));
        artists.add(new Artist("Dave","NewYork"));
        artists.stream().filter(artist -> {
            System.out.println(artist.getName());
            return artist.isFrom("London");
        });
    }
}

执行该端代码,没有任何输出。像这种只过滤不计数的,filter只刻画出了Stream,但并无产生新的集合的方法,咱们称之为惰性求值方法;而像count这样最终会从Stream产生值的方法叫作及早求值方法。

咱们再把上述代码改回求值。

public class ComeFromStream {
    public static void main(String[] args) {
        List<Artist> artists = new ArrayList<>();
        artists.add(new Artist("Martin","London"));
        artists.add(new Artist("Shirly","Beijing"));
        artists.add(new Artist("Dilon","London"));
        artists.add(new Artist("Dave","NewYork"));
        long count = artists.stream().filter(artist -> {
            System.out.println(artist.getName());
            return artist.isFrom("London");
        }).count();
        System.out.println(count);
    }
}

运行结果

Martin
Shirly
Dilon
Dave
2

判断一个操做是惰性求值仍是及早求值很简单:只需看它的返回值。若是返回值是Stream,那么是惰性求值;若是返回值是另外一个值或为空,那么就是及早求值。整个过程和建造者模式有共通之处。建造者模式使用一系列操做设置属性和配置,最后调用build方法,这时,对象才被真正建立。

相关文章
相关标签/搜索