Java 8 中的 Streams API 和 Lambada表达式

为什么需要 Stream
Stream 作为 Java 8 的一大亮点,它与 java.io 包里的 InputStream 和 OutputStream 是完全不同的概念。它也不同于 StAX 对 XML 解析的 Stream,也不是 Amazon Kinesis 对大数据实时处理的 Stream。Java 8 中的 Stream 是对集合(Collection)对象功能的增强,它专注于对集合对象进行各种非常便利、高效的聚合操作(aggregate operation),或者大批量数据操作 (bulk data operation)。Stream API 借助于同样新出现的 Lambda 表达式,极大的提高编程效率和程序可读性。同时它提供串行和并行两种模式进行汇聚操作,并发模式能够充分利用多核处理器的优势,使用 fork/join 并行方式来拆分任务和加速处理过程。通常编写并行代码很难而且容易出错, 但使用 Stream API 无需编写一行多线程的代码,就可以很方便地写出高性能的并发程序。所以说,Java 8 中首次出现的 java.util.stream 是一个函数式语言+多核时代综合影响的产物。

准备
创建一个测试类

public class Student{

    /**
     * id
     */
    private int id;
    /**
     * 姓名
     */
    private String name;
    /**
     * 年龄
     */
    private int age;
    /**
     * 手机
     */
    private String phone;

    //省略 get /set /toString
}

1.Lambda 表达式
Lambda 表达式的基础语法:Java8中引入了一个新的操作符 “->” 该操作符称为箭头操作符或 Lambda 操作符
箭头操作符将 Lambda 表达式拆分成两部分:
左侧:Lambda 表达式的参数列表
右侧:Lambda 表达式中所需执行的功能, 即 Lambda 体

语法介绍

序号描述示例
1无参数,无返回值() -> System.out.println(“Hello Lambda!”)
2有一个参数,并且无返回值(x) -> System.out.println(x)
3若只有一个参数,小括号可以省略不写x -> System.out.println(x)
4有两个以上的参数,有返回值,并且 Lambda 体中有多条语句Comparator com = (x, y) -> {System.out.println(“函数式接口”);return Integer.compare(x, y);};
5若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写return 和 大括号都可以省略不写 Comparator com = (x, y) -> Integer.compare(x, y);
6Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断”(Integer x, Integer y) -> Integer.compare(x, y);

1.1遍历集合
1.1.1 List遍历

  @Test
    public void test1() {
     List<Student> studentList = new ArrayList<Student>();
        studentList.add(new Student(1, "张三", 11, "13333345671"));
        studentList.add(new Student(2, "李四", 10, "13333345672"));
        studentList.add(new Student(3, "王五", 12, "13333345673"));
        studentList.add(new Student(4, "赵六", 11, "13333345674"));
        studentList.add(new Student(5, "大黑", 13, "13333345675"));
        studentList.add(new Student(6, "大白", 10, "13333345676"));

        // for Each 遍历
        for (Student stu : studentList) {
            System.out.println(stu);
        }

        //java 8   Lambda 遍历,stu 代表List里的Student对象
        studentList.forEach(stu -> {
            System.out.println(stu);
        });
    }

1.1.2 Map遍历

 @Test
    public void test2() {
        Map<String, Integer> items = new HashMap<String, Integer>();
        items.put("A", 10);
        items.put("B", 20);
        items.put("C", 30);
        items.put("D", 40);
        items.put("E", 50);
        items.put("F", 60);

        //遍历 map
        for (Map.Entry<String, Integer> entry : items.entrySet()) {
            System.out.println("map-key : " + entry.getKey() + " map-value : " + entry.getValue());
        }

        //java 8  lambda 表达式遍历 ,k,与 v 分别代表map集合的 key与value
        items.forEach((k, v) -> System.out.println("map-key  : " + k + " map-value : " + v));
    }

2.Stream API
2.1过滤
2.1.1 filter()过滤与collect()

示例:过滤出年龄< 13 的 学生

 private static List<Student> studentList = new ArrayList<Student>();

    static {
        studentList.add(new Student(1, "张三", 11, "13333345671"));
        studentList.add(new Student(2, "李四", 10, "13333345672"));
        studentList.add(new Student(3, "王五", 12, "13333345673"));
        studentList.add(new Student(4, "赵六", 11, "13333345674"));
        studentList.add(new Student(5, "大黑", 15, "13333345675"));
        studentList.add(new Student(6, "大白", 10, "13333345676"));
    }

    /**
     * 过滤出年龄< 13 的 学生
     * filter()与collect()
     */
    @Test
    public void test1() {
        List<Student> studentFilterList = studentList.stream() // 转化为流
                .filter(student -> student.getAge() < 13) // 只过滤出 <13 的学生
                .collect(Collectors.toList()); //输出流收集回List中,为空的情况下返回空集合
        System.out.println("集合大小 : " + studentFilterList.size());
        System.out.println("返回结果 : " + studentFilterList.toString());
    }

2.1.2多种条件过滤
示例:过滤出年龄为10,并且名称为"大白"的学生

  /**
     * 多种条件过滤
     * filter()与collect()
     */
    @Test
    public void test2() {
        List<Student> studentFilterList = studentList.stream() // 转化为流
                .filter(stu -> { //多种条件过滤
                    if (10 == stu.getAge() && "大白".equals(stu.getName())) {
                        return true;
                    }
                    return false;
                }) // 只过滤出 <13 的学生
                .collect(Collectors.toList()); //输出流收集回List中,为空的情况下返回空集合

        System.out.println("集合大小 : " + studentFilterList.size());
        System.out.println("返回结果 : " + studentFilterList.toString());
    }

2.1.3对象转Integer或String
示例1:学生年龄Integer 集

 /**
     * 获得 学生年龄Integer 集  
     * 并去重处理
     * filter()、map()、collect()、distinct()
     */
    @Test
    public void test3() {
        List<Integer> studentAgeList = studentList.stream() // 转化为流
                .map(Student::getAge) //流转化为Integer,方法引用写法,即使用 Student中 getAge() 方法
                .distinct() // 去重 处理
                .collect(Collectors.toList()); //输出流收集回List中,为空的情况下返回空集合
        System.out.println("集合大小 : " + studentAgeList.size());
        System.out.println("返回结果 : " + studentAgeList.toString());
    }

   /**
     * 获得 学生名称String 集
     * 并去重处理
     * filter()、map()、collect()、distinct()
     */
    @Test
    public void test4() {
        List<String> studentAgeList = studentList.stream() // 转化为流
                .map(Student::getName) //流转化为String
                .distinct() // 去重 处理
                .collect(Collectors.toList()); //输出流收集回List中,为空的情况下返回空集合
        System.out.println("集合大小 : " + studentAgeList.size());
        System.out.println("返回结果 : " + studentAgeList.toString());
    }

注:Student::getAge 方法引用写法,即Student中 getAge() 方法

2.1.4 返回集合第一条

   /**
     * 集合返回一条
     * findFirst()、orElse()
     */
    @Test
    public void test5() {
        Student student = studentList.stream() // 转化为流
                .findFirst()//返回第一条
                .orElse(new Student()); //不存在情况下返回空对象,或者返回null,示例 :orElse(null)
        System.out.println(student);
    }

2.5 返回集合任意一条

    /**
     * filter()、findAny()、orElse()
     */
    @Test
    public void test7() {
        Student student = studentList.stream() // 转化为流
                .filter(stu -> { //多种条件过滤
                    if (10 == stu.getAge() && "大白".equals(stu.getName())) {
                        return true;
                    }
                    return false;
                }) // 过滤年龄等于10
                .findAny() //任意找到一条符合的立即返回
                .orElse(new Student()); //不存在情况下返回空对象,或者返回null,例如 :orElse(null)

        System.out.println(student);
    }

2.2.1 对象集合分组

    /**
     * 对象集合分组
     * 对一个List<Student>根据年龄进行分组
     */
    @Test
    public void test2() {
        Map<Integer, List<Student>> result =
                studentList.stream().collect(Collectors.groupingBy(Student::getAge));

        System.out.println("集合大小 : " + result.size());
        System.out.println("返回结果 : " + result.toString());
    }

参考:https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Go语言(也称为Golang)是由Google开发的一种静态强类型、编译型的编程语言。它旨在成为一门简单、高效、安全和并发的编程语言,特别适用于构建高性能的服务器和分布式系统。以下是Go语言的一些主要特点和优势: 简洁性:Go语言的语法简单直观,易于学习和使用。它避免了复杂的语法特性,如继承、重载等,转而采用组合和接口来实现代码的复用和扩展。 高性能:Go语言具有出色的性能,可以媲美C和C++。它使用静态类型系统和编译型语言的优势,能够生成高效的机器码。 并发性:Go语言内置了对并发的支持,通过轻量级的goroutine和channel机制,可以轻松实现并发编程。这使得Go语言在构建高性能的服务器和分布式系统时具有天然的优势。 安全性:Go语言具有强大的类型系统和内存管理机制,能够减少运行时错误和内存泄漏等问题。它还支持编译时检查,可以在编译阶段就发现潜在的问题。 标准库:Go语言的标准库非常丰富,包含了大量的实用功能和工具,如网络编程、文件操作、加密解密等。这使得开发者可以更加专注于业务逻辑的实现,而无需花费太多时间在底层功能的实现上。 跨平台:Go语言支持多种操作系统和平台,包括Windows、Linux、macOS等。它使用统一的构建系统(如Go Modules),可以轻松地跨平台编译和运行代码。 开源和社区支持:Go语言是开源的,具有庞大的社区支持和丰富的资源。开发者可以通过社区获取帮助、分享经验和学习资料。 总之,Go语言是一种简单、高效、安全、并发的编程语言,特别适用于构建高性能的服务器和分布式系统。如果你正在寻找一种易于学习和使用的编程语言,并且需要处理大量的并发请求和数据,那么Go语言可能是一个不错的选择。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值