Java8新特性 - lambda、stream、optional

Java8新特性 - lambda、stream、optional

    

    几种 lambda 语法构成:(参数1, 参数2 ... ) -> { 逻辑代码语句 };  (参数1, 参数2 ...)-> expression ;

    在 jdk 内置的接口都加上了 @FunctionInterface 注解,表明该接口是一个函数式接口,同时支持 lambda 表达式。

        

    下面是 java8中 java.util.Function 包下的 常用类的 lambda 表达式的练习。

    方法推导 Method Reference      语法格式:类 : : 方法名

因为在自定义的Consumer中,是接受一个字符串,然后通过输出打印,不需要返回值。

而 System.out.println() 方法也是接受一个object对象,做打印输出,不需要返回值,因此可以进行方法推导。

    

 

 

2、stream 流

注意:stream流只能使用一次。不能重复使用

 

创建Stream的几种方式:

package createStream;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.Supplier;
import java.util.stream.Stream;

public class CreateStream {

    public static void main(String[] args) {
        createStreamFormList().forEach(System.out::println);
        System.out.println("========");
        createStreamFormStreamOfMethod().forEach(System.out::println);
        System.out.println("========");
        createStreamFromArrays().forEach(System.out::println);
        System.out.println("========");
        createStreamFromFile();
        System.out.println("========");
        createStreamFromIterator().forEach(System.out::println);
        System.out.println("========");
        createStreamFromGenerator().forEach(System.out::println);
        System.out.println("========");
        createStreamFromMyObj();

    }

    public static Stream<String> createStreamFormList() {
        List<String> nameList = Arrays.asList("Alex", "John", "Mike", "David");
        return nameList.stream();
    }

    public static Stream<String> createStreamFormStreamOfMethod() {
        return Stream.of("Alex", "John", "Mike", "David");
    }

    public static Stream<String> createStreamFromArrays() {
        return Arrays.stream(new String[]{"Alex", "John", "Mike", "David"});
    }

    public static void createStreamFromFile() {
        Path path = Paths.get("G:\my_project\java8\java8-sharing\src\main\java\createStream\CreateStream.java");
        try {
            Files.lines(path, StandardCharsets.UTF_8).forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Stream<Integer> createStreamFromIterator() {
        return Stream.iterate(0, (n) -> {return n + 2;}).limit(10);
    }

    public static Stream<Double> createStreamFromGenerator() {
        return Stream.generate(Math::random).limit(10);
    }

    public static Stream<MyObj> createStreamFromMyObj() {
        return Stream.generate(new MyObj(100, "name")).limit(10);
    }

    /**
     * 自定义的对象 MyObj,作为生成的 Stream 的 generate方法的参数
     */
    public static class MyObj implements Supplier<MyObj> {
        private int id;
        private String name;

        public MyObj() {
        }

        public MyObj(int id, String name) {
            int index = new Random().nextInt(id);
            this.id = index;
            this.name = name + "->" + index;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

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

        @Override
        public String toString() {
            return "MyObj{" +
                    "id=" + id +
                    ", name="" + name + """ +
                    "}";
        }

        @Override
        public MyObj get() {
            return this;
        }
    }
}

 

Stream流的常用 API 练习:

filter方法使用:

 

map方法使用:

 

match方法:

 

reduce方法:

 

find方法:    find方法主要是讲返回值 Optional<T>。 该类贼强大

 

NumericStream 和 Stream 之间的转换: 下面的案例是 Integer 拆箱转 Int,减少空间

 

Java8 in Action -- Stream综合练习

package stream;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

/**
 * 来自 Java8 in Action 书籍第55.5的练习题
 */
public class StreamPractice {

    public static void main(String[] args) {

        Trader raoul = new Trader("Raoul", "Cambridge");
        Trader mario = new Trader("Mario", "Milan");
        Trader alan = new Trader("Alan", "Cambridge");
        Trader brian = new Trader("Brian", "Cambridge");

        List<Transaction> transactions = Arrays.asList(
                new Transaction(brian, 2011, 300),
                new Transaction(raoul, 2012, 1000),
                new Transaction(raoul, 2011, 400),
                new Transaction(mario, 2012, 710),
                new Transaction(mario, 2012, 700),
                new Transaction(alan, 2012, 950)
        );

        /*List<Boolean> collect = transactions.stream().map((transaction -> transaction.getYear() == 2011))
                .collect(toList());
        System.out.println(collect);*/

        // question one -- Find all transactions in the year 2011 and sort them by value (small to high).
        List<Transaction> transactionList = transactions.stream().
                // 筛选出年份是 2011                 filter(transaction -> transaction.getYear() == 2011)
                // 提取value
                .sorted(Comparator.comparingInt(Transaction::getValue))
                // stream转成新的集合
                .collect(toList());
        System.out.println(transactionList);

        // question two -- What are all the unique cities where the traders work?
        List<String> collect = transactions.stream()
                .map(transaction -> transaction.getTrader().getCity())
                .distinct()
                .collect(toList());
        System.out.println(collect);


        // question three -- Find all traders from Cambridge and sort them by name.
        List<String> stringList = transactions.stream()
                // 筛选出城市是 Cambridge                 .filter(transaction -> transaction.getTrader().getCity().equals("Cambridge"))
                // 排序
                .sorted(Comparator.comparing(transaction -> transaction.getTrader().getName()))
                // 提取名字
                .map(transaction -> transaction.getTrader().getName())
                // 去重
                .distinct()
                // stream转成新的集合
                .collect(toList());
        System.out.println(stringList);

        // question four -- Return a string of all traders’ names sorted alphabetically.
        List<String> stringList1 = transactions.stream()
                // 获取名字集合
                .map(transaction -> transaction.getTrader().getName())
                // name 去重
                .distinct()
                // 转为字符数组
                // .map(name -> name.split(""))
                // 数组再转成流
                // .flatMap(Arrays::stream)
                // 排序
                .sorted(String::compareTo)
                // stream转成新的集合
                .collect(toList());
        System.out.println(stringList1);

        // question five -- Are any traders based in Milan?
        long count = transactions.stream()
                // 筛选出城市是 Milan                 .filter(transaction -> transaction.getTrader().getCity().equals("Milan"))
                // 提取名字
                .map(transaction -> transaction.getTrader().getName())
                // 去重
                .distinct()
                // 统计
                .count();
        List<String> milan = transactions.stream()
                // 筛选出城市是 Milan                 .filter(transaction -> transaction.getTrader().getCity().equals("Milan"))
                // 提取名字
                .map(transaction -> transaction.getTrader().getName())
                // 去重
                .distinct()
                // stream转成新的集合
                .collect(toList());
        System.out.println(count);
        System.out.println(milan);

        // question six -- Print all transactions’ values from the traders living in Cambridge.
        List<Integer> cambridge = transactions.stream()
                //  筛选出城市是 Cambridge                 .filter(transaction -> transaction.getTrader().getCity().equals("Cambridge"))
                .map(Transaction::getValue)
                // stream转成新的集合
                .collect(toList());
        System.out.println(cambridge);

        // question seven -- What’s the highest value of all the transactions?
        Optional<Integer> max = transactions.stream()
                //  筛选出城市是 Cambridge                 .map(Transaction::getValue)
                // 比较出最大值
                .max(Integer::compareTo);
        System.out.println(max.get());

        // question eight -- Find the transaction with the smallest value.
        Optional<Transaction> max1 = transactions.stream()
                // 比较出最大值
                .min(Comparator.comparingInt(Transaction::getValue));
        System.out.println(max1.get());
    }
}

 

3、Optional类:源码Source Code不算多,推荐先看一遍Optional类的所有方法