Java8新特性

Lambda表达式

  • Lambda表达式需要函数式接口的支持。
  • 函数式接口:接口中只有一个抽象方法,可以使用@FunctionalInterface注解修饰。

格式一:无参数,无返回值

public class Lambda01 {
    public static void main(String[] args) {
        Runnable runnable = ()-> System.out.println("hello lambda");
        runnable.run();
    }
}

格式二:一个参数,无返回值

public class Lambda02 {
    public static void main(String[] args) {
        Consumer<String> consumer = (s) -> System.out.println(s);
        consumer.accept("hello lambda");
    }
}

格式三:多个参数,有返回值,并且lambda体中有多条语句

public class Lambda03 {
    public static void main(String[] args) {
        Comparator<Integer> comparator = (x, y) -> {
            System.out.println("hello lambda");
            return Integer.compare(x, y);
        };
    }
}

格式四:lambda中只有一条语句

public class Lambda04 {
    public static void main(String[] args) {
        Comparator<Integer> comparator= (x, y) -> Integer.compare(x, y);
    }
}

四大内置核心函数式接口

Consumer<T>:消费型接口

  • 有一个参数,没有返回值。
@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

    /**
     * Returns a composed {@code Consumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @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); };
    }
}
public class Function01 {
    public static void main(String[] args) {
        Consumer<Integer> consumer = (num) -> System.out.println(num);
        consumer.accept(100);
    }
}

Supplier<T>:供给型接口

  • 没有参数,有一个返回值。
@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}
public class Function02 {
    public static void main(String[] args) {
        Supplier<Integer> supplier = () -> (int)(Math.random() * 10);
        System.out.println(supplier.get());
    }
}

Function<T, R> :函数型接口

  • 有一个参数,一个返回值。
@FunctionalInterface
public interface Function<T, R> {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);

    /**
     * Returns a composed function that first applies the {@code before}
     * function to its input, and then applies this function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed 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));
    }

    /**
     * Returns a composed function that first applies this function to
     * its input, and then applies the {@code after} function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed 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));
    }

    /**
     * Returns a function that always returns its input argument.
     *
     * @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;
    }
}
public class Function03 {
    public static void main(String[] args) {
        Function<String, Integer> function = (str) -> str.length();
        System.out.println(function.apply("123456"));
    }
}

Predicate<T>:断言型接口

  • 一个参数,布尔类型返回值。
@FunctionalInterface
public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * AND of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code false}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @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);
    }

    /**
     * Returns a predicate that represents the logical negation of this
     * predicate.
     *
     * @return a predicate that represents the logical negation of this
     * predicate
     */
    default Predicate<T> negate() {
        return (t) -> !test(t);
    }

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * OR of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code true}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @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);
    }

    /**
     * Returns a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}.
     *
     * @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 Function04 {
    public static void main(String[] args) {
        Predicate<String> predicate = (str) -> str.length() > 2;
        System.out.println(predicate.test("123456"));
    }
}

方法引用与构造器引用

方法引用

  • 若Lambda体中的内容有方法已经实现了,可以使用“方法引用 ”。
  • 方法引用是Lambda表达式的另外一种表现形式。主要有三种语法格式:
    • 对象::实例方法名
    • 类::静态方法名
    • 类::实例方法名
  • Lambda体中调用方法的参数列表与返回值类型,要与函数式接口中抽象方法的函数列表和返回值类保持一致。
public class Client01 {
    public static void main(String[] args) {

        Consumer<String> consumer = System.out::println;
        consumer.accept("123456");

        Comparator<Integer> comparator = Integer::compare;
        System.out.println(comparator.compare(1, 2));
    }
}

构造器引用

  • 格式:ClassName::new
  • 调用的构造器的参数列表要与函数式接口中抽象方法的参数列表保持一致。
public class User {

    private String name;

    public User(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}
public class Client02 {
    public static void main(String[] args) {
        Function<String, User> function = User::new;
        User user = function.apply("张三");
        System.out.println(user);
    }
}

Stream API

  • Stream的三个操作步骤:创建Stream、中间操作、终止操作。

创建Stream

public class Stream01 {
    public static void main(String[] args) {
        //第一种方式,通过Collection系列集合提供的stream()或parallelStream()
        List<String> list = new ArrayList<>();
        Stream<String> stream1 = list.stream();
        stream1.forEach(System.out::println);//终止操作
        //第二种方式,通过Arrays中的静态方法stream()获取数组流
        String[] strings1 = new String[5];
        Stream<String> stream2 = Arrays.stream(strings1);
        stream2.forEach(System.out::println);
        //第三种方式,通过Stream类中的静态方法of()
        String[] strings2 = new String[5];
        Stream<String> stream3 = Stream.of(strings2);
        stream3.forEach(System.out::println);
        //第四种方式,创建无限流
        //迭代
        Stream<Integer> stream4 = Stream.iterate(0, (x) -> x + 2);
        stream4.forEach(System.out::println);
        //生成
        Stream<Double> stream5 = Stream.generate(Math::random);
        stream5.forEach(System.out::println);
    }
}

筛选与切片

public class User {

    private String name;
    private int age;
    private float score;

    public User() {
    }

    public User(String name, int age, float score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public float getScore() {
        return score;
    }

    public void setScore(float score) {
        this.score = score;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return age == user.age && Float.compare(user.score, score) == 0 && Objects.equals(name, user.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age, score);
    }
}
public class Stream02 {
    public static void main(String[] args) {
        /*
        * filter:从流中排除某些元素
        * limit:使元素不超过给定数量
        * skip(n):跳过元素,返回一个扔掉了前n个元素的流
        * distinct:筛选,通过hashCode()和equals()去除重复元素
        * */
        List<User> list = Arrays.asList(
                new User("张三", 12, 96),
                new User("李四", 22, 23),
                new User("王五", 56, 100),
                new User("孙悟空", 47, 88),
                new User("猪八戒", 90, 12.3f),
                new User("沙和尚", 84, 96),
                new User("沙和尚", 84, 96));
        list.stream()
                .filter((user) -> user.getAge() > 50 && user.getScore() > 80)
                .forEach(System.out::println);
        System.out.println("===========================");
        list.stream()
                .filter((user) -> user.getAge() > 50)
                .limit(2)
                .forEach(System.out::println);
        System.out.println("===========================");
        list.stream()
                .skip(3)
                .forEach(System.out::println);
        System.out.println("===========================");
        list.stream()
                .distinct()
                .forEach(System.out::println);
    }
}

映射与排序

public class Stream03 {
    public static void main(String[] args) {
        /*
        * map:将元素转换成其他形式或提示信息。接收一个函数作为参数,该函数会被应用到每个元素上,并映射成一个新的元素。
        * sorted
        * */
        List<User> list = Arrays.asList(
                new User("张三", 12, 96),
                new User("李四", 22, 23),
                new User("王五", 56, 100),
                new User("孙悟空", 47, 88),
                new User("猪八戒", 90, 12.3f),
                new User("沙和尚", 84, 96),
                new User("沙和尚", 84, 96));
        list.stream()
                .map((user) -> user.getAge() + 1)
                .forEach(System.out::println);
        System.out.println("=========================");
        list.stream()
                .map(User::getName)
                .forEach(System.out::println);
        System.out.println("=========================");
        list.stream()
                .sorted(Comparator.comparingInt(User::getAge))
                .forEach(System.out::println);
    }
}

查找与匹配

public class Stream04 {
    public static void main(String[] args) {
        /*
        * allMatch:检查是否匹配所有元素
        * anyMatch:检查是否至少匹配一个元素
        * noneMatch:检查是否没有匹配所有元素
        * findFirst:返回第一个元素
        * findAny:返回当前流中任意元素
        * count:返回元素个数
        * max:返回最大值
        * min:返回最小值
        * */
        List<User> list = Arrays.asList(
                new User("张三", 12, 96),
                new User("李四", 22, 23),
                new User("王五", 56, 100),
                new User("孙悟空", 47, 88),
                new User("猪八戒", 90, 12.3f),
                new User("沙和尚", 84, 96),
                new User("沙和尚", 84, 96));
        System.out.println(list.stream()
                .allMatch((user) -> user.getAge() > 20));
        System.out.println("=============================");
        System.out.println(list.stream()
                .anyMatch((user) -> user.getAge() > 20));
        System.out.println("=============================");
        System.out.println(list.stream()
                .noneMatch((user) -> user.getAge() > 20));
        System.out.println("=============================");
        System.out.println(list.stream()
                .findFirst().get());
        System.out.println("=============================");
        System.out.println(list.stream()
                .findAny().get());
        System.out.println("=============================");
        System.out.println(list.stream()
                .count());
        System.out.println("=============================");
        System.out.println(list.stream()
                .max(Comparator.comparingInt(User::getAge)).get());
        System.out.println("=============================");
        System.out.println(list.stream()
                .min(Comparator.comparingInt(User::getAge)).get());
    }
}

归约与收集

public class Stream05 {
    public static void main(String[] args) {
        /*
         * reduce:将流中元素反复结合起来,得到一个值
         * collect :将流转换为其他形式。
         * */
        List<User> list = Arrays.asList(
                new User("张三", 12, 96),
                new User("李四", 22, 23),
                new User("王五", 56, 100),
                new User("孙悟空", 47, 88),
                new User("猪八戒", 90, 12.3f),
                new User("沙和尚", 84, 96),
                new User("沙和尚", 84, 96));
        System.out.println(list.stream()
                .map(User::getScore)
                .reduce(Float::sum)
                .get());
        System.out.println("================================");
        System.out.println(list.stream()
                .map(User::getName)
                .collect(Collectors.toList()));
        System.out.println("================================");
        list.stream()
                .map(User::getName)
                .collect(Collectors.toCollection(LinkedList::new))
                .forEach(System.out::println);
    }
}

并行流

public class Stream06 {
    public static void main(String[] args) {
        System.out.println(LongStream.rangeClosed(0, 1000000000L)
                .parallel()
                .reduce(Long::sum));
    }
}

Optional

public class Optional01 {
    public static void main(String[] args) {
        User user = new User("诸葛亮", 13, 16);
        test(Optional.empty());
        test(Optional.of(user));
    }
    public static void test(Optional<User> user){
        System.out.println(user.orElse(new User("不知好歹", 12, 16)));
    }
}

时间与日期

public class DateTime01 {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
        DateTimeFormatter dateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println(dateTime.format(now));
        LocalDateTime sunday = now.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
        System.out.println(sunday);
        LocalDateTime days = now.plusDays(1);
        System.out.println(days);
        System.out.println(now.getYear());

        Instant instant = Instant.now();//UTC时间
        System.out.println(instant.toEpochMilli());

        Instant instant1 = Instant.now();
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Instant instant2 = Instant.now();
        Duration between = Duration.between(instant1, instant2);
        System.out.println(between.getSeconds());
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值