java8新特性

Java8 内置的四大核心函数式接口

Consumer< T > : 消费型接口 void accept(T t);

消费,有去无回,没有返回值

/**
 * 消费型接口
 */
@Test
void test() {
    happy(10000,m -> System.out.println("Nugoah喜欢大宝剑,每次消费" + m + "元"));
}

void happy(double money, Consumer<Double> consumer) {
    consumer.accept(money);
}
Supplier< T > : 供给型接口 T ger();
/**
 * 供给型接口
 * 示例:随机产生指定随机数并放入集合
 */
@Test
void test1() {
    List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100));
    numList.forEach(System.out::println);
}
public List<Integer> getNumList(int num, Supplier<Integer> supplier) {
    ArrayList<Integer> list = new ArrayList<>();
    for (int i = 0; i < num; i++) {
        Integer n = supplier.get();
        list.add(n);
    }
    return list;
}
Function<T, R> : 函数型接口 R apply(T t);
/**
 * 函数型接口
 * 需求:处理字符串
 */
@Test
void test2() {
    String str = "\t\t\t  我大java威武   ";
    String s = strHandler(str, String::trim);//取非空字符串
    System.out.println(s);
    String s1 = strHandler(s, String::toUpperCase);//转大写
    System.out.println(s1);
    String s2 = s1.substring(2, 6);//截取字符串
    System.out.println(s2);
}
public String strHandler(String str, Function<String, String> function) {
    return function.apply(str);
}
Predicate< T > : 断言型接口 boolean test(T t);
/**
 * 断言型接口
 * 需求:过滤字符串,输出长度大于3的字符串
 */
@Test
void test3() {
    List<String> list = Arrays.asList("Hello", "world", "Lambda", "www", "ok");
    List<String> strList = filterStr(list, s -> s.length() > 3);
    strList.forEach(System.out::println);
}
public List<String> filterStr(List<String> list, Predicate<String> predicate) {
    ArrayList<String> strings = new ArrayList<>();
    for (String string : list) {
        if (predicate.test(string)){
            strings.add(string);
        }
    }
    return strings;
}

image-20220228132117950

方法引用:

若Lambda 体中的内容有方法已经实现了,我们可以使用“方法引用”(可以理解为方法引用是Lambda表达式的另外一种表现形式)

主要有三种语法格式:

  1. 对象::实例方法名
  2. 类::静态方法名
  3. 类::实例方法名

Stream的三个操作步骤:

  1. 创建Stream
  2. 中间操作
  3. 终止操作(终端操作)
创建Stream
@Test
void test4() {
    // 1.可以通过Collection 系列集合提供的 stream() 或 parallelStream()
    ArrayList<String> list = new ArrayList<>();
    Stream<String> stream1 = list.stream();

    // 2. 通过 Arrays 中的静态方法 stream() 获取数组流
    Employee[] emps = new Employee[10];
    Stream<Employee> stream2 = Arrays.stream(emps);

    // 3.通过 Stream 类中的静态方法 of()
    Stream<String> stream3 = Stream.of("aa", "bb", "cc");

    // 4.创建无限流
    //迭代
    Stream<Integer> stream4 = Stream.iterate(0, (x) -> x + 2);
    stream4.forEach(System.out::println);

    //生成
    Stream.generate(() -> Math.random()).forEach(System.out::println);
}
中间操作
筛选与切片
  • filter——接收 Lambda ,从流中排除某些元素
  • limit——截断流,使其元素不超过给定数量。
  • skip(n)——跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流。与limit(n) 互补
  • distinct——筛选,通过流所生成元素的hashCode() 和 equals() 去除重复元素

image-20220228220030285

filte
@Test
// 内部迭代:迭代操作由 Stream API 完成
public void test1() {
    // 中间操作:不会执行任何操作
    Stream<Employee> stream = employees.stream()
        .filter((e) -> {
            // 在执行中间操作时,不会执行任何操作(中间操作没有执行)
            System.out.println("Stream API 的中间操作")
            return e.getAge() > 35;
        });
    // 终止操作:一次性执行全部内容,即“即惰性求值”
    stream.forEach(System.out::println);
}
// 外部迭代:有我们自己完成
@Test
public void test2() {
    Iterator<Employee> it = employees.iterator();
    while(it.hasNext()) {
        System.out.println(it.next());
    }
}

image-20220228215851365

limit
@Test
public void test3() {
    employees.stream()
        .filter((e) -> {
            System.out.println("短路!");
            return e.getSalary() > 5000;
        })
        .limit(2)
        .forEach(System.out::println);
}

image-20220228223258513

skip(n)
@Test
public void test4() {
    employees.stream()
        .filter((e) -> e.getSalary() > 5000)
        // 扔掉前两个元素,跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流。与limit(n) 互补
        .skip(2)
        .forEach(System.out::println);
}
distinct
@Test
public void test4() {
    employees.stream()
        .filter((e) -> e.getSalary() > 5000)
        .skip(2)
        // 筛选,通过流所生成元素的hashCode() 和 equals() 去除重复元素
        .distinct()
        .forEach(System.out::println);
}

注意:筛选,通过流所生成元素的hashCode() 和 equals() 去除重复元素

​ 所以,必须重写hashCode() 和 equals() 方法

映射
/**
 * 映射
 * map -- 接收 Lambda ,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
 * flatMap -- 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有的流连接成一个流
 */
@Test
public void test01() {
    List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");

    list.stream()
        .map(String::toUpperCase)//{ {a, a, a} {b, b, b} } ,流里面放流,类似add()
        .forEach(System.out::println);
    System.out.println("----------------------");

    Stream<Stream<Character>> stream = list.stream()
        .map(TestStream01::filterCharacter);

    stream.forEach((sm) -> sm.forEach(System.out::println));

    System.out.println("----------------------");

    Stream<Character> sm = list.stream()
        .flatMap(TestStream01::filterCharacter);//{a, a, a, b, b, b,...} 把所有的流连接成一个流,类似addAll()
    sm.forEach(System.out::println);
}

public static Stream<Character> filterCharacter(String str) {
    List<Character> list = new ArrayList<>();
    for (Character ch : str.toCharArray()) {
        list.add(ch);
    }
    return list.stream();
}
排序
  • sorted() --自然排序(Comparable)
  • sorted(Comparator com)-- 定制排序(Comparator)
@Test
public void test7() {
	List<String> list = Arrays.asList("ccc", "aaa", "bbb", "ddd");
	list.stream()
        .sorted()
        .forEach(System.out::println);
    System.out.println("------------------------");
    
    employees.stream()
        sorted((e1, e2) -> {
            if(e1.getAge().equals(e2.getAge())){
                return e1.getName().compareTo(e2.getName());
            }else{
                return e1.getAge().compareTo(e2.getAge());// 升序
                return -e1.getAge().compareTo(e2.getAge());// 降序
            }
        })
}
终止操作
  • allMatch – 检查是否匹配所有元素
  • anyMatch – 检查是否至少匹配一个元素
  • noneMatch – 检查是否没有匹配所有元素
  • findFirst – 返回第一个元素
  • findAny – 返回当前流中的任意元素
  • count – 返回流中元素的总个数
  • max – 返回流中最大值
  • min – 返回流中最小值
List<Employee> employees = Arrays.asList(
        new Employee("张三", 18, 9999.99, Employee.Status.FREE),
        new Employee("李四", 58, 5555.55, Employee.Status.BUSY),
        new Employee("王五", 26, 3333.33, Employee.Status.VOCATION),
        new Employee("赵六", 36, 6666.66, Employee.Status.FREE),
        new Employee("田七", 12, 8888.88, Employee.Status.BUSY)
);

@Test
public void test1() {
    /*
    检查是否匹配所有元素
     */
    boolean b1 = employees.stream()
            .allMatch(e -> e.getSalary().equals(Employee.Status.BUSY));
    System.out.println(b1); // 输出false
    /*
    检查是否至少匹配一个元素
     */
    boolean b2 = employees.stream()
            .anyMatch(e -> e.getSalary().equals(Employee.Status.BUSY));
    System.out.println(b2);

    /*
    检查是否没有匹配所有元素
     */
    boolean b3 = employees.stream()
            .noneMatch(e -> e.getSalary().equals(Employee.Status.BUSY));
    System.out.println(b3);
    /*
    返回第一个元素
     */
    Optional<Employee> op = employees.stream() // 如果最终的结果可能为空,则返回Optional
            .sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
            .findFirst();
    System.out.println(op);

    /*
    返回当前流中的任意元素
     */
    Optional<Employee> op2 = employees.stream()
            .filter(e -> e.getStatus().equals(Employee.Status.FREE))
            .findAny();
    System.out.println(op2);

    /*
    返回流中元素的个数
     */
    long count = employees.stream()
            .count();
    System.out.println(count);
    /*
    返回流中元素的最大值
     */
    Optional<Employee> max = employees.stream()
            .max(Comparator.comparingDouble(Employee::getSalary));
    System.out.println(max);
    /*
    返回流中元素的最小值
     */
    Optional<Double> min = employees.stream()
            .map(Employee::getSalary) // 经过map映射,流中的数据都变成了Double类型的salary,可以直接使用方法引用
            .min(Double::compare);
    System.out.println(min.get());
}
规约

image-20220301151135503

List<Employee> employees = Arrays.asList(
        new Employee("张三", 18, 9999.99, Employee.Status.FREE),
        new Employee("李四", 58, 5555.55, Employee.Status.BUSY),
        new Employee("王五", 26, 3333.33, Employee.Status.VOCATION),
        new Employee("赵六", 36, 6666.66, Employee.Status.FREE),
        new Employee("田七", 12, 8888.88, Employee.Status.BUSY)
);
/**
     * 规约
     * reduce(T identity, BinaryOperator) / reduce(BinaryOperator) -- 可以将流中元素反复结合起来,得到一个值
     *           起始值      二元运算
     */
    @Test
    public void test2() {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
        Integer num = list.stream()
                .reduce(0, (x, y) -> x + y);
//                .reduce(0, Integer::sum)
        System.out.println(num);

        Optional<Double> op = employees.stream()
                .map(Employee::getSalary)
                .reduce(Double::sum);
        System.out.println(op.get());
    }

image-20220301151106774

image-20220301151118546

收集

image-20220301151700101

/**
 * 收集
 * collect -- 将流转换为其他形式。接收一个Collector接口的实现,用于给Stream中元素做汇总的方法
 */
@Test
public void test3() {
    List<String> list = employees.stream()
            .map(Employee::getName)
            .collect(Collectors.toList());
    list.forEach(System.out::println);
    System.out.println("-----------------------");

    HashSet<String> hs = employees.stream()
            .map(Employee::getName)
            .collect(Collectors.toCollection(HashSet::new));
    hs.forEach(System.out::println);
}

@Test
public void test4() {
    // 总数
    Long count = employees.stream()
            .collect(Collectors.counting());
    System.out.println(count);

    System.out.println("-----------------");

    // 平均值
    Double avg = employees.stream()
            .collect(Collectors.averagingDouble(Employee::getSalary));
    System.out.println(avg);

    System.out.println("------------------");

    // 总和
    Double sum = employees.stream()
            .collect(Collectors.summingDouble(Employee::getSalary));
    System.out.println(sum);

    //工资最大的成员
    Optional<Employee> max = employees.stream()
            .collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
    System.out.println(max.get());
    //最小工资
    Optional<Double> min = employees.stream()
            .map(Employee::getSalary)
            .collect(Collectors.minBy(Double::compare));
    System.out.println(min.get());
}
// 多级分组
    @Test
    public void test5() {
        Map<Employee.Status, Map<String, List<Employee>>> map = employees.stream()
                .collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
                    if (e.getAge() <= 35) {
                        return "青年";
                    } else if (e.getAge() <= 50) {
                        return "中年";
                    } else {
                        return "老年";
                    }
                })));
        map.forEach((key, value) -> System.out.println(key + ":" + value));
    }

    // 分区
    @Test
    public void test6() {
        Map<Boolean, List<Employee>> map = employees.stream()
                .collect(Collectors.partitioningBy(e -> e.getSalary() > 8000));
        map.forEach((key, value) -> System.out.println(key + "::" + value));
    }

    @Test
    public void test7() {
        DoubleSummaryStatistics dds = employees.stream()
                .collect(Collectors.summarizingDouble(Employee::getSalary));
        System.out.println(dds.getSum());
        System.out.println(dds.getAverage()); // 平均值
        System.out.println(dds.getMax());
    }

    @Test
    public void test8() {
        String str = employees.stream()
                .map(Employee::getName)
                .collect(Collectors.joining(",", "===", "==="));
        System.out.println(str);
    }

image-20220301220031221

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

oah1021

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值