Java Stream 的常用API

Java Stream 的常用API

遍历(forEach)

package com.liudashuai;

import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<Person> userList = new ArrayList<>();
        userList.add(new Person("段誉",25));
        userList.add(new Person("萧峰",40));
        userList.add(new Person("虚竹",30));
        userList.add(new Person("无涯子",100));
        userList.add(new Person("慕容复",35));
        userList.add(new Person("云中鹤",45));

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

        userList.stream().forEach(u -> {
            u.setName("天龙八部-" + u.getName());
        });

        System.out.println(userList);
    }
}
class Person{
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    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;
    }

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

在这里插入图片描述

筛选(filter)

package com.liudashuai;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Test {
    public static void main(String[] args) {
        List<Person> userList = new ArrayList<>();
        userList.add(new Person("段誉",25));
        userList.add(new Person("萧峰",40));
        userList.add(new Person("虚竹",30));
        userList.add(new Person("无涯子",100));
        userList.add(new Person("慕容复",35));
        userList.add(new Person("云中鹤",45));

        List<Person> collect =
                userList.stream().filter(user -> (user.getAge() > 30 && user.getName().length() >2)).collect(Collectors.toList());

        System.out.println(collect);
    }
}
class Person{
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    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;
    }

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

在这里插入图片描述

查找(findAny/findFirst)

package com.liudashuai;

import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<Person> userList = new ArrayList<>();
        userList.add(new Person("段誉",25));
        userList.add(new Person("萧峰",41));
        userList.add(new Person("萧峰",42));
        userList.add(new Person("萧峰",43));
        userList.add(new Person("虚竹",30));
        userList.add(new Person("无涯子",100));
        userList.add(new Person("慕容复",35));
        userList.add(new Person("云中鹤",45));

        Person user = userList.stream().filter(u -> u.getName().equals("阿紫")).findAny().orElse(new Person("无",0));
        System.out.println(user);

        Person user1 = userList.stream().filter(u -> u.getName().equals("阿紫")).findAny().orElse(null);
        System.out.println(user1);

        Person user2 = userList.stream().filter(u -> u.getName().equals("萧峰")).findAny().orElse(null);
        System.out.println(user2);

        Person user3 = userList.stream().filter(u -> u.getName().equals("萧峰")).findFirst().orElse(null);
        System.out.println(user3);
    }
}
class Person{
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    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;
    }

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

在这里插入图片描述

  1. findFirst() 方法根据命名,我们可以大致知道是获取Optional流中的第一个元素。
  2. findAny() 方法是获取Optional 流中任意一个,存在随机性,其实这里也是获取元素中的第一个,因为是并行流。

注意:在串行流中,findFirst和findAny返回同样的结果;但在并行流中,由于多个线程同时处理,findFirst可能会返回处理结果中的第一个元素,而findAny会返回最先处理完的元素。所以并行流里面使用findAny会更高效。这里并行下findFirst可能返回的不是第一个符合条件的元素吗?我不知道,但是,不重要,因为用得场景不多,因为多线程下,谁是处理结果中的第一个元素一般不重要,因为谁都可能是第一个,所以这里我不去了解findFirst是否可能返回的不是第一个符合条件的元素了。

总之就是串行流下,findFirst和findAny结果一样,并行流下,findAny效率更高,且并行流一般不在意谁是第一个,所以我建议平时使用findAny。

.orElse(null)表示如果一个都没找到返回null。

orElse()中可以塞默认值。如果找不到就会返回orElse中你自己设置的默认值。比如:上面的.orElse(new Person(“无”,0))

转换/去重(map/distinct)

package com.liudashuai;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Test {
    public static void main(String[] args) {
        List<Person> userList = new ArrayList<>();
        userList.add(new Person("段誉",25));
        userList.add(new Person("萧峰",41));
        userList.add(new Person("萧峰",42));
        userList.add(new Person("虚竹",30));
        userList.add(new Person("无涯子",100));
        userList.add(new Person("慕容复",35));
        userList.add(new Person("云中鹤",45));

        List<String> nameList = userList.stream().map(Person::getName).collect(Collectors.toList());
        System.out.println(nameList);
        List<String> nameList2 = userList.stream().map(Person::getName).distinct().collect(Collectors.toList());
        System.out.println(nameList2);
    }
}
class Person{
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    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;
    }

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

在这里插入图片描述

map的作用:是将输入一种类型,转化为另一种类型,通俗来说:就是将输入类型变成另一个类型。

跳过(limit/skip)

package com.liudashuai;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Test {
    public static void main(String[] args) {
        List<Person> userList = new ArrayList<>();
        userList.add(new Person("段誉",25));
        userList.add(new Person("萧峰",41));
        userList.add(new Person("虚竹",30));
        userList.add(new Person("无涯子",100));
        userList.add(new Person("慕容复1",35));
        userList.add(new Person("慕容复2",35));
        userList.add(new Person("慕容复3",35));

        //跳过第一个
        List<Person> collect = userList.stream().skip(1).collect(Collectors.toList());
        System.out.println(collect);
        //只输出前两个元素
        List<Person> collect2 = userList.stream().limit(2).collect(Collectors.toList());
        System.out.println(collect2);
        //跳过前3个元素,然后输出3个元素。可以代替sql中的limit。
        List<Person> collect3 = userList.stream().skip(3).limit(3).collect(Collectors.toList());
        System.out.println(collect3);
    }
}
class Person{
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    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;
    }

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

在这里插入图片描述

最大值/最小值/平均值(reduce)

package com.liudashuai;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class Test {
    public static void main(String[] args) {
        List<Person> userList = new ArrayList<>();
        userList.add(new Person("段誉",25));
        userList.add(new Person("萧峰",41));
        userList.add(new Person("虚竹",30));
        userList.add(new Person("无涯子",100));
        userList.add(new Person("慕容复",35));

        System.out.println("求和");
        Integer sum1 = userList.stream().map(Person::getAge).reduce(0, Integer::sum);
        System.out.println(sum1);

        int sum2 = userList.stream().mapToInt(Person::getAge).sum();
        System.out.println(sum2);

        Integer sum3 = userList.stream().collect(Collectors.summingInt(Person::getAge));
        System.out.println(sum3);

        System.out.println("最大值");
        Optional<Integer> max1 = userList.stream().map(Person::getAge).collect(Collectors.toList())
                .stream().reduce((v1, v2) -> v1 > v2 ? v1 : v2);
        System.out.println(max1.get());

        Optional<Integer> max2 = userList.stream().map(Person::getAge).collect(Collectors.toList())
                .stream().reduce(Integer::max);
        System.out.println(max2.get());

        int max3 = userList.stream().mapToInt(Person::getAge).max().getAsInt();
        System.out.println(max3);

        System.out.println("最小值");
        Optional<Integer> min = userList.stream().map(Person::getAge).collect(Collectors.toList())
                .stream().reduce(Integer::min);
        System.out.println(min.get());

        int min2 = userList.stream().mapToInt(Person::getAge).min().getAsInt();
        System.out.println(min2);

        System.out.println("平均值");
        Double averaging1 = userList.stream().collect(Collectors.averagingDouble(Person::getAge));
        System.out.println(averaging1);

        double averaging2 = userList.stream().mapToInt(Person::getAge).average().getAsDouble();
        System.out.println(averaging2);
    }
}
class Person{
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    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;
    }

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

在这里插入图片描述

mapToInt是 Stream API中一个非常有用的方法。它的主要作用是将一个 Stream 转换成一个IntStream,使得可以更加方便地对数字流进行处理。

IntStream中的一些常用方法如下:

  1. sum()
  2. max()
  3. min()
  4. average()

这些方法上面案例里面也有演示。

如果要操作的元素不是int,是double,我们也可以用mapToDouble也行。

package com.liudashuai;

import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<Person> userList = new ArrayList<>();
        userList.add(new Person("段誉",161.5));
        userList.add(new Person("萧峰",171.2));
        userList.add(new Person("虚竹",167.2));
        userList.add(new Person("无涯子",184.2));
        userList.add(new Person("慕容复",178.0));

        double sum = userList.stream().mapToDouble(Person::getHeight).sum();//和
        double max = userList.stream().mapToDouble(Person::getHeight).max().getAsDouble();//最高
        double min = userList.stream().mapToDouble(Person::getHeight).min().getAsDouble();//最矮
        double average = userList.stream().mapToDouble(Person::getHeight).average().getAsDouble();//平均
        System.out.println(sum);
        System.out.println(max);
        System.out.println(min);
        System.out.println(average);
    }
}
class Person{
    private String name;
    private double height;

    public Person(String name, double height) {
        this.name = name;
        this.height = height;
    }

    public String getName() {
        return name;
    }

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

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", height=" + height +
                '}';
    }
}

在这里插入图片描述

统计(count/counting)

package com.liudashuai;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Test {
    public static void main(String[] args) {
        List<Person> userList = new ArrayList<>();
        userList.add(new Person("段誉",25));
        userList.add(new Person("萧峰",41));
        userList.add(new Person("虚竹",30));
        userList.add(new Person("无涯子",100));
        userList.add(new Person("虚竹",30));
        userList.add(new Person("慕容复",35));

        Long collect = userList.stream().filter(p -> p.getName() == "虚竹").collect(Collectors.counting());
        System.out.println(collect);

        long count = userList.stream().filter(p -> p.getAge() >= 50).count();
        System.out.println(count);
    }
}
class Person{
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    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;
    }

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

在这里插入图片描述

排序(sorted)

package com.liudashuai;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class Test {
    public static void main(String[] args) {
        List<Person> userList = new ArrayList<>();
        userList.add(new Person("1",25));
        userList.add(new Person("2",41));
        userList.add(new Person("33",30));
        userList.add(new Person("11",100));
        userList.add(new Person("55",30));
        userList.add(new Person("22",35));

        List<Person> collect =
                userList.stream().sorted(Comparator.comparing(Person::getAge).reversed()).collect(Collectors.toList());
        System.out.println(collect);

        List<Person> collect2 =
                userList.stream().sorted(Comparator.comparing(Person::getAge)).collect(Collectors.toList());
        System.out.println(collect2);

        List<Person> collect3 =
                userList.stream().sorted(Comparator.comparing(Person::getName)).collect(Collectors.toList());
        System.out.println(collect3);

        List<Person> collect4 = userList.stream().sorted((e1, e2) -> {
            return Integer.compare(Integer.parseInt(e1.getName()), Integer.parseInt(e2.getName()));
        }).collect(Collectors.toList());
        System.out.println(collect4);
    }
}
class Person{
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    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;
    }

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

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/142224.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

数据可视化模板案例:制造业提高生产力的关键

一、模板背景 在这个信息爆炸的时代&#xff0c;数据对于企业的成功至关重要。制造业作为全球经济的重要组成部分&#xff0c;如何有效利用数据提高生产效率、降低成本、优化决策&#xff0c;已成为行业关注的焦点。 二、方案思路 配⾊ - 科技蓝&#xff0c;贴合⼯业主题。 …

RDkit | 安装报错及使用

关于RDKit的学习及介绍&#xff1a; RDKit安装 基础教程&#xff1a;[Getting Started with RDKit in Python] RDkit四&#xff1a;数据处理过程中smiles编码的清洗统一化 reticulate-R Interface to Python 在RStudio中加载 rdkit.Chem和rdkit.Chem.rdmolops 时&#xff0c;报…

Linux 本地zabbix结合内网穿透工具实现安全远程访问浏览器

前言 Zabbix是一个基于WEB界面的提供分布式系统监视以及网络监视功能的企业级的开源解决方案。能监视各种网络参数&#xff0c;保证服务器系统的安全运营&#xff1b;并提供灵活的通知机制以让系统管理员快速定位/解决存在的各种问题。 本地zabbix web管理界面限制在只能局域…

Android R.fraction

来源 我是在看Android10原生代码&#xff0c;绘制状态栏蓝牙电量相关类中第一次看到R.fraction的&#xff0c;如类BatteryMeterDrawable <fraction name"battery_button_height_fraction">10%</fraction> mButtonHeightFraction context.getResources(…

网络运维Day13

文章目录 部署web服务器部署虚拟机web1安装依赖包解压NGINX压缩包初始化编译编译安装查看验证配置动静分离 部署虚拟机web2安装依赖包解压NGINX压缩包初始化编译编译安装查看验证配置动静分离 配置NGINX七层代理测试健康检查功能 配置NGINX四层代理部署代理服务器 总结 部署web…

2022年09月 Python(五级)真题解析#中国电子学会#全国青少年软件编程等级考试

Python等级考试(1~6级)全部真题・点这里 一、单选题(共25题,每题2分,共50分) 第1题 已知字符串:s=“语文,数学,英语”,执行print(s.split(“,”))语句后结果是?( ) A: [‘语文’, ‘数学’, ‘英语’] B: [语文, 数学, 英语] C: [‘语文, 数学, 英语’] D: [‘语…

使用opencv实现图像的畸形矫正:仿射变换

1 仿射变换 1.1 什么是仿射变换 在图像处理中&#xff0c;经常需要对图像进行各种操作如平移、缩放、旋转、翻转等&#xff0c;这些都是图像的仿射变换。图像仿射变换又称为图像仿射映射&#xff0c;是指在几何中&#xff0c;一个向量空间进行一次线性变换并接上一个平移&…

Git分支与Git标签详解

目录 前言 一、Git分支&#xff08;Branch&#xff09; 1.分支的概念 2.分支的常用操作 3.Git 分支管理 二、Git标签&#xff08;Tag&#xff09; 1.标签的概念 2.标签的类型 3.标签的常用操作 4.Git标签管理 前言 在软件开发过程中&#xff0c;版本管理是非常重要的一…

asp.net图书管理系统

asp.net图书管理系统 基本操作图书管理 读者管理 借书 修改资料 修改密码 说明文档 运行前附加数据库.mdf&#xff08;或sql生成数据库&#xff09; 主要技术&#xff1a; 基于C#winform架构和sql server数据库 功能模块&#xff1a; 图书管理 读者管理 借书 修改资料 修改…

C/C++交换输出 2021年9月电子学会青少年软件编程(C/C++)等级考试一级真题答案解析

目录 C/C交换输出 一、题目要求 1、编程实现 2、输入输出 二、算法分析 三、程序编写 四、程序说明 五、运行结果 六、考点分析 C/C交换输出 2021年9月 C/C编程等级考试一级编程题 一、题目要求 1、编程实现 输入两个整数a,b&#xff0c;将它们交换输出 2、输入输…

【系统安装】ubuntu20.04启动盘制作,正经教程,小白安装教程,百分百成功安装

1.所需材料&#xff1a; 64GBU盘&#xff08;其实8g和16g也可以&#xff09; 2.制作U盘启动盘 使用windows制作ubuntu 20.04启动盘 1&#xff09;下载制作工具&#xff1a;Rufus&#xff1a;Rufus - 轻松创建 USB 启动盘 2&#xff09;插入用来做启动盘的U盘 3&#xff0…

【Vue】过滤器Filters

hello&#xff0c;我是小索奇&#xff0c;精心制作的Vue系列持续发放&#xff0c;涵盖大量的经验和示例&#xff0c;如对您有用&#xff0c;可以点赞收藏哈 过滤器 filters过滤器已从Vue 3.0中删除&#xff0c;不再支持了&#xff0c;这里可以作为了解进行学习 vue3要精简代码&…

指标类型(一):北极星指标、虚荣指标

每个产品都有很多指标&#xff0c;每个指标都反映了对应业务的经营情况。但是在实际业务经营中&#xff0c;却要求我们在不同的产品阶段寻找到合适的指标&#xff0c;让这个指标可以代表当前产品阶段的方向和目标&#xff0c;让这个指标不仅对业务经营团队&#xff0c;而且对产…

GCN代码讲解

这里写的有点抽象&#xff0c;所以具体的可以参照下面代码块中的注释&#xff1a; def load_data(path"../data/cora/", dataset"cora"):"""Load citation network dataset (cora only for now)"""print(Loading {} datase…

Git忽略文件.gitignore的使用

1.为什么使用? 当你使用git add .的时候有没有遇到把你不想提交的文件也添加到了缓存中去&#xff1f;比如项目的本地配置信息&#xff0c;如果你上传到Git中去其他人pull下来的时候就会和他本地的配置有冲突&#xff0c;所以这样的个性化配置文件我们一般不把它推送到git服务…

C++编写的多线程自动爬虫程序

以下是一个使用C编写的爬虫程序&#xff0c;用于爬取Python进行多线程跑数据的内容。本示例使用了Python的requests库来发送HTTP请求&#xff0c;并使用cheeseboy的爬虫ipIP库来设置爬虫ip信息。以下是详细代码和步骤&#xff1a; #include <iostream> #include <stri…

MySQL 人脸向量,欧几里得距离相似查询

前言 如标题&#xff0c;就是通过提取的人脸特征向量&#xff0c;写一个欧几里得 SQL 语句&#xff0c;查询数据库里相似度排前 TOP_K 个的数据记录。做法虽然另类&#xff0c;业务层市面上有现成的面部检索 API&#xff0c;技术层现在有向量数据库。 用 MySQL 关系型存储 128 …

人工智能基础_机器学习026_L1正则化_套索回归权重衰减梯度下降公式_原理解读---人工智能工作笔记0066

然后我们继续来看套索回归,也就是线性回归,加上了一个L1正则化对吧,然后我们看这里 L1正则化的公式是第二个,然后第一个是原来的线性回归,然后 最后一行紫色的,是J= J0+L1 对吧,其实就是上面两个公式加起来 然后我们再去看绿色的 第一行,其实就是原来线性回归的梯度下降公式…

uniapp 小程序 身份证 和人脸视频拍摄

使用前提&#xff1a; 已经在微信公众平台的用户隐私协议&#xff0c;已经选择配置“摄像头&#xff0c;录像”等权限 开发背景&#xff1a;客户需要使用带有拍摄边框的摄像头 &#xff0c;微信小程序的方法无法支持&#xff0c;使用camera修改 身份证正反面&#xff1a; <…
最新文章