Java8新特性

2020-07-06  本文已影响0人  sgy_j

Stream

类Stream是对象和原始数据类型上的流。Stream在几个方面与集合不同:

stream操作分为中间操作终端操作,合并以形成pipeline

下面对常见的stream操作进行介绍

根据指定模型,计算源内数据,得到一个最终结果

对例子进行解释

Function接口

一个Function<T, R>对象相当于一个函数,其中T是函数参数类型,R是函数返回值类型,等号后面的lambda表达式为函数逻辑。

R apply(T t)相当于函数调用,t为调用函数式传入的参数值。

public class FunctionTest {
    public static void main(String[] args) {
        Integer num = 5;
        System.out.println(functionAdd(num)); // 6
        System.out.println(add(num)); // 6
    }

    public static Integer functionAdd(Integer num){
        Function<Integer, Integer> function = x -> x + 1;
        return function.apply(num);
    }

    public static Integer add (Integer num) {
        return num + 1;
    }
}

Function<V, R> compose()、Function<V, R> andThen()相当于函数组合,源码如下。

/**
     * @return a composed function that first applies the {@code before}
     * function and then applies this function
     */
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
    Objects.requireNonNull(before);
    return (V v) -> apply(before.apply(v));
}
/**
     * @return a composed function that first applies this function and then
     * applies the {@code after} function
     */
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
    Objects.requireNonNull(after);
    return (T t) -> after.apply(apply(t));
}

根据方法名获取对象方法值

@Data
@AllArgsConstructor
public class Person {
    private Double age;
    private Double height;
}
@AllArgsConstructor
@Getter
public enum PersonAttribute {
    AGE("age", Person::getAge),
    HEIGHT("height", Person::getHeight);

    private String name;
    private Function<Person, Double> getAttribute;

    public static PersonAttribute ofName(String name) {
        try {
            return Arrays.stream(PersonAttribute.values())
                    .filter(personAttribute -> personAttribute.name.equals(name.trim()))
                    .findFirst()
                    .orElseThrow(() -> new Exception("input attribute's name error:" + name));
        } catch (Exception exception){
            exception.printStackTrace();
        }
        return null;
    }
}
public class Test {
    public static void main(String[] args) {
        Person person = new Person(18D, 160D);
        Scanner scanner = new Scanner(System.in);
        PersonAttribute personAttribute = PersonAttribute.ofName(scanner.nextLine());
        System.out.println(personAttribute.getGetAttribute().apply(person));
    }
}

::

https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps

上一篇下一篇

猜你喜欢

热点阅读