微信app网站,wordpress中is,大气有格局的公司名字,网站优化推广服务java之lambda表达式stream流式编程操作集合 1 stream流概念1.1 中间操作1.1.1 无状态操作1.1.2 有状态操作 1.2 终端操作1.2.1 非短路操作1.2.2 短路操作 2 steam流的生成2.1 方式一#xff1a;数组转为stream流2.2 方式二#xff1a;集合转为steam流2.3 方式三#xf… java之lambda表达式stream流式编程操作集合 1 stream流概念1.1 中间操作1.1.1 无状态操作1.1.2 有状态操作 1.2 终端操作1.2.1 非短路操作1.2.2 短路操作  2 steam流的生成2.1 方式一数组转为stream流2.2 方式二集合转为steam流2.3 方式三Stream.builder创建stream流2.4 方式四使用 Stream.of 方法2.5 方式五从文件创建流2.6 方式六生成无限流 3 无状态的中间操作3.1 distinct3.2 limit3.3 skip3.4 sorted3.5 组合使用 4 有状态的中间操作4.1 filter重要4.2 map重要4.3 flatMap4.4 peek4.5 组合使用 5 非短路的终端操作5.1 forEach5.2 toArray5.3 reduce重要5.4 collect重要5.5 min、max、count5.6 组合使用 6 短路的终端操作6.1 anyMatch6.2 allMatch6.3 noneMatch6.4 findFirst6.5 findAny6.6 组合使用 7 并行流8 总结 1 stream流概念 
简单来讲Stream流是一种用于处理数据集合的高级迭代器它可以对集合中的元素进行各种操作如过滤、映射、排序等。通过使用Stream API我们可以以声明式的方式处理数据而无需显式地编写循环和条件语句。 Stream流的操作分为两种中间操作和终端操作。 
1.1 中间操作 
是指对每个元素独立进行操作不依赖于其他元素的状态。它们不会改变流中的元素本身而是创建一个新的Stream对象来表示转换后的结果。常见的无状态中间操作有map、filter、flatMap等。 
1.1.1 无状态操作 
无状态操作不会改变流中的元素也不会改变流的状态这些操作可以并行执行因为它们不依赖于流中的其他元素。例如 
distinct返回去重的Stream。limit限制从流中获得前n个数据返回前n个元素数据组成的Stream流。skip跳过前n个数据返回第n个元素后面数据组成的Stream。sorted返回一个排序的Stream。 
1.1.2 有状态操作 
有状态操作会改变流的状态或者依赖于流中的其他元素。这些操作不能并行执行因为它们需要访问或修改流的状态。 例如 
filter过滤流过滤流中的元素返回一个符合条件的Streammap转换流将一种类型的流转换为另外一种流。mapToInt、mapToLong、mapToDouble 返回int、long、double基本类型对应的Streampeek:主要用来查看流中元素的数据状态该方法主要用于调试方便debug查看Stream内进行处理的每个元素。仅在对流内元素进行操作时peek才会被调用当不对元素做任何操作时peek自然也不会被调用了flatMap简单的说就是一个或多个流合并成一个新流。 
1.2 终端操作 
是对数据进行最终处理的操作它们会消耗掉Stream并产生一个结果或者副作用如输出到控制台。一旦执行了终端操作Stream就不能再被使用。常见的终端操作有collect、forEach、reduce等。 
1.2.1 非短路操作 
非短路操作会处理流中的所有元素并返回一个结果。 如 
forEach循环操作Stream中数据。toArray返回流中元素对应的数组对象。reduce聚合操作用来做统计将流中元素反复结合起来统计计算得到一个值.。collect聚合操作封装目标数据将流转换为其他形式接收如List、Set、Map、Array。min、max、count聚合操作最小值最大值总数量。 
1.2.2 短路操作 
短路操作会在满足某个条件时提前结束处理并返回一个结果。例如 
anyMatch短路操作有一个符合条件返回true。allMatch所有数据都符合条件返回true。noneMatch所有数据都不符合条件返回true。findFirst短路操作获取第一个元素。findAny短路操作获取任一元素。 
2 steam流的生成 
2.1 方式一数组转为stream流 
int [] arr  {1,2,3,4,5,6,7,8,9,10};       
Arrays.stream(arr).forEach(System.out::println);2.2 方式二集合转为steam流 
ListInteger list  Arrays.asList(1,2,3,4,5,6,7,8,9,10);
list.stream().forEach(System.out::println);2.3 方式三Stream.builder创建stream流 
Stream.builder创建stream流允许你逐步构建一个流 
Stream.BuilderInteger builder  Stream.builder();// 添加元素到流中
builder.add(1);
builder.add(2);
builder.add(3);// 构建流
StreamInteger stream  builder.build();// 使用流
stream.forEach(System.out::println);2.4 方式四使用 Stream.of 方法 
Stream.of 方法可以接受一系列元素并返回一个包含这些元素的流。 
StreamString words  Stream.of(apple, banana, orange);
words.forEach(System.out::println);2.5 方式五从文件创建流 
可以使用 Files.lines 方法从文件中创建流。 
try (StreamString stream  Files.lines(Paths.get(file.txt))) {stream.forEach(System.out::println);
} catch (IOException e) {e.printStackTrace();
}2.6 方式六生成无限流 
可以使用 Stream.generate 或 Stream.iterate 方法来生成无限流。 
StreamDouble randomNumbers  Stream.generate(Math::random);
randomNumbers.forEach(System.out::println);
StreamInteger oddNumbers  Stream.iterate(1, n - n  2);
oddNumbers.forEach(System.out::println);3 无状态的中间操作 
3.1 distinct 
返回一个去重的流即去除重复的元素 
StreamInteger distinctStream  Stream.of(1, 2, 2, 3, 4, 4, 5).distinct();
distinctStream.forEach(System.out::println);
//输出结果123453.2 limit 
限制从流中获得前n个数据返回前n个元素数据组成的流 
StreamInteger limitedStream  Stream.of(1, 2, 3, 4, 5).limit(3);
limitedStream.forEach(System.out::println);
//输出结果1233.3 skip 
StreamInteger skippedStream  Stream.of(1, 2, 3, 4, 5).skip(2);
skippedStream.forEach(System.out::println);
//输出结果3453.4 sorted 
//正序排序从小到大
StreamInteger sortedStream  Stream.of(5, 3, 1, 4, 2).sorted();
sortedStream.forEach(System.out::println);
//输出结果12345//逆序排序从大到小Comparator.reverseOrder() 创建了一个逆序比较器然后传递给 sorted 方法从而实现了逆序排序
StreamInteger sortedStream  Stream.of(5, 3, 1, 4, 2).sorted(Comparator.reverseOrder());
sortedStream.forEach(System.out::println);
//输出结果543213.5 组合使用 
这段代码首先去重然后排序跳过第一个元素最后限制结果流只包含前三个元素 
StreamInteger stream  Stream.of(1, 2, 2, 3, 4, 4, 5).distinct().sorted().skip(1).limit(3);
stream.forEach(System.out::println);
//输出结果234测试实体类 
Data
public class Person {private int id;private String name; // 姓名private int salary; // 薪资private int age; // 年龄private String sex; //性别private String area; // 地区private ListPerson employeeList; //下属public Person() {}// 构造方法public Person(String name, int salary, int age,String sex,String area) {this.name  name;this.salary  salary;this.age  age;this.sex  sex;this.area  area;}// 构造方法public Person(int id, String name, int salary, int age, String sex, String area) {this.id  id;this.name  name;this.salary  salary;this.age  age;this.sex  sex;this.area  area;}Overridepublic String toString() {return Person{ name  name  \ , salary  salary , age  age , sex  sex  \ , area  area  \ };}
}// 创建一个List来存储Person对象
ListPerson personList  new ArrayList();// 创建8个Person对象并添加到列表中
personList.add(new Person(1, Alice, 5000, 30, Female, New York));
personList.add(new Person(2, Bob, 6000, 35, Male, Los Angeles));
personList.add(new Person(3, Charlie, 5500, 28, Male, Chicago));
personList.add(new Person(4, Diana, 7000, 40, Female, Miami));
personList.add(new Person(5, Ethan, 4800, 25, Male, Houston));
personList.add(new Person(6, Fiona, 5300, 32, Female, Seattle));
personList.add(new Person(7, George, 6200, 38, Male, Boston));
personList.add(new Person(8, Hannah, 5900, 29, Female, San Francisco));4 有状态的中间操作 
4.1 filter重要 
// 1. 筛选出所有女性
ListPerson females  personList.stream().filter(person - person.getSex().equalsIgnoreCase(female)).collect(Collectors.toList());
System.out.println(女性列表:   females);// 2. 筛选出薪资高于5000的人员
ListPerson highSalary  personList.stream().filter(person - person.getSalary()  5000).collect(Collectors.toList());
System.out.println(薪资高于5000的人员:   highSalary);// 3. 筛选出年龄在30岁及以上的人员
ListPerson ageAbove30  personList.stream().filter(person - person.getAge()  30).collect(Collectors.toList());
System.out.println(年龄在30岁及以上的人员:   ageAbove30);// 4. 筛选出居住在特定城市例如New York的人员
ListPerson livingInNewYork  personList.stream().filter(person - person.getArea().equalsIgnoreCase(New York)).collect(Collectors.toList());
System.out.println(居住在纽约的人员:   livingInNewYork);// 5. 筛选出名字以A开头的人员
ListPerson namesStartingWithA  personList.stream().filter(person - person.getName().startsWith(A)).collect(Collectors.toList());
System.out.println(名字以A开头的人员:   namesStartingWithA);4.2 map重要 
// 1. 提取所有人的名字
ListString names  personList.stream().map(Person::getName).collect(Collectors.toList());
System.out.println(所有人的名字:   names);// 2. 提取所有人的薪资
ListInteger salaries  personList.stream().map(Person::getSalary).collect(Collectors.toList());
System.out.println(所有人的薪资:   salaries);// 3. 提取所有人的地区
ListString cities  personList.stream().map(Person::getArea).collect(Collectors.toList());
System.out.println(所有人的城市:   cities);// 4. 提取所有人的年龄并加上10
ListInteger agesPlus10  personList.stream().map(person - person.getAge()  10).collect(Collectors.toList());
System.out.println(所有人的年龄加十:   agesPlus10);// 5. 提取薪资信息并格式化为字符串
ListString salaryInfo  personList.stream().map(person - person.getName()  的薪资为:   person.getSalary()).collect(Collectors.toList());
System.out.println(薪资信息:   salaryInfo);4.3 flatMap 
flatMap 是 Java Stream API 中的一个非常有用的方法通常用于将多个流扁平化为一个流。在处理 Person 对象时我们可以使用 flatMap 来进行一些复杂的数据结构操作。以下是一些示例展示如何在你的 personList 上使用 flatMap。 
ListString flatMappedList  personList.stream().map(person - person.getName()) // 将Person对象转换为名字.flatMap(name - Stream.of(name, name.toUpperCase())) // 将名字转换为名字和名字的大写形式.collect(Collectors.toList());4.4 peek 
personList.stream().peek(person - System.out.println(Before filter:   person)) // 打印每个Person对象.filter(person - person.getAge()  30) // 过滤年龄大于30的Person对象.peek(person - System.out.println(After filter:   person)) // 打印过滤后的Person对象.collect(Collectors.toList());4.5 组合使用 
// 使用Stream API处理personList
ListString combinedList  personList.stream().filter(person - person.getAge()  30) // 过滤年龄大于30的Person对象.map(person - person.getName()) // 将Person对象转换为名字.flatMap(name - Stream.of(name, name.toUpperCase())) // 将名字转换为名字和名字的大写形式.peek(System.out::println) // 打印每个名字.collect(Collectors.toList()); // 收集结果到一个List中 
5 非短路的终端操作 
5.1 forEach 
personList.stream().forEach(person - System.out.println(person.getName()));personList.stream().forEachOrdered(person - System.out.println(person.getName()));5.2 toArray 
Object[] array  personList.stream().toArray();5.3 reduce重要 
// 1. 计算总薪资
int totalSalary  personList.stream().map(Person::getSalary).reduce(0, Integer::sum);
System.out.println(总薪资:   totalSalary);// 2. 计算平均薪资
OptionalDouble averageSalary  personList.stream().map(Person::getSalary).reduce((a, b) - a  b).map(sum - sum / (double) personList.size());
System.out.println(平均薪资:   averageSalary.orElse(0.0));// 3. 查找最高薪资
OptionalInteger maxSalary  personList.stream().map(Person::getSalary).reduce(Integer::max);
System.out.println(最高薪资:   maxSalary.orElse(0));// 4. 查找最低薪资
OptionalInteger minSalary  personList.stream().map(Person::getSalary).reduce(Integer::min);
System.out.println(最低薪资:   minSalary.orElse(0));// 5. 计算年龄之和
int totalAge  personList.stream().map(Person::getAge).reduce(0, Integer::sum);
System.out.println(总年龄:   totalAge);5.4 collect重要 
//收集到 List集合
ListString names  personList.stream().map(Person::getName).collect(Collectors.toList());
//收集到 Set集合
SetString cities  personList.stream().map(Person::getArea).collect(Collectors.toSet());
//收集到 Map集合
MapInteger, String idToNameMap  personList.stream().collect(Collectors.toMap(Person::getId, Person::getName));MapInteger, Person idToPersonMap  personList.stream().collect(Collectors.toMap(Person::getId, v - v));
//收集到自定义集合
ListPerson sortedList  personList.stream().sorted(Comparator.comparing(Person::getAge)).collect(Collectors.toList());
//使用 Collectors.joining 连接字符串
String namesString  personList.stream().map(Person::getName).collect(Collectors.joining(, ));
//Collectors.groupingBy
MapString, ListPerson cityToPeopleMap  personList.stream().collect(Collectors.groupingBy(Person::getArea));
//使用 Collectors.partitioningBy 分区
MapBoolean, ListPerson isAdultMap  personList.stream().collect(Collectors.partitioningBy(person - person.getAge()  18));
//使用 Collectors.summarizingInt 计算统计信息
IntSummaryStatistics salarySummary  personList.stream().collect(Collectors.summarizingInt(Person::getSalary));
double average  salarySummary.getAverage();//平均值
int max  salarySummary.getMax();//最大值
long count  salarySummary.getCount();//计数
int min  salarySummary.getMin();//最小值
long sum  salarySummary.getSum();//求和5.5 min、max、count 
OptionalPerson maxSalaryPerson  personList.stream().max(Comparator.comparing(Person::getSalary));
OptionalPerson minAgePerson  personList.stream().min(Comparator.comparing(Person::getAge));
long count  personList.stream().count();5.6 组合使用 
这段代码首先计算所有 Person 对象的工资总和然后找到年龄最大的 Person 对象最后将所有 Person 对象的名字收集到一个 List 中。 
int totalSalary  personList.stream().mapToInt(Person::getSalary).reduce(0, Integer::sum);OptionalPerson oldestPerson  personList.stream().max(Comparator.comparing(Person::getAge));ListString names  personList.stream().map(Person::getName).collect(Collectors.toList()); 
6 短路的终端操作 
6.1 anyMatch 
boolean hasFemale  personList.stream().anyMatch(person - Female.equals(person.getGender()));6.2 allMatch 
boolean allAdults  personList.stream().allMatch(person - person.getAge()  18);6.3 noneMatch 
boolean noRetired  personList.stream().noneMatch(person - person.getAge()  65);6.4 findFirst 
OptionalPerson firstPerson  personList.stream().findFirst();6.5 findAny 
OptionalPerson anyPerson  personList.stream().findAny();6.6 组合使用 
这段代码首先检查是否存在女性然后找到第一个成年人最后将所有成年人的名字收集到一个 List 中。 
boolean hasFemale  personList.stream().anyMatch(person - Female.equals(person.getGender()));OptionalPerson firstAdult  personList.stream().filter(person - person.getAge()  18).findFirst();ListString names  personList.stream().filter(person - person.getAge()  18).map(Person::getName).collect(Collectors.toList());7 并行流 
并行流可以提高处理大数据集时的性能。Java Stream API 的并行处理是基于 Java 的 Fork/Join 框架实现的。Fork/Join 框架是 Java 7 引入的一种并行计算框架它可以将一个大任务拆分成多个小任务然后在多个处理器上并行执行这些小任务最后将结果合并。 
在 Stream API 中并行流是通过 parallelStream() 方法创建的。当你调用 parallelStream() 方法时Stream API 会创建一个 ForkJoinTask并将其提交给 ForkJoinPool 执行。ForkJoinPool 是一个特殊的线程池它使用工作窃取算法来平衡任务执行从而提高并行处理效率。 
String allNames  personList.parallelStream().map(Person::getName).collect(Collectors.joining(, ));
System.out.println(All Names (Parallel):   allNames);8 总结 
Stream API 的主要特点包括 
简洁性Stream API 提供了一种简洁的方式来处理集合数据使得代码更加易读、易写。可读性Stream API 的操作可以链式调用使得代码更加清晰、易读。并行处理Stream API 支持并行处理可以充分利用多核处理器的能力。惰性求值Stream API 的操作是惰性求值的即只有在需要结果时才会执行操作。无状态操作Stream API 的无状态操作不会改变流中的元素也不会改变流的状态。有状态操作Stream API 的有状态操作会改变流的状态或者依赖于流中的其他元素。短路操作Stream API 的短路操作会在满足某个条件时提前结束处理并返回一个结果。终端操作Stream API 的终端操作会处理流中的所有元素并返回一个结果。 创作不易不妨点赞、收藏、关注支持一下各位的支持就是我创作的最大动力❤️  文章转载自: http://www.morning.zfwjh.cn.gov.cn.zfwjh.cn http://www.morning.svtxeu.com.gov.cn.svtxeu.com http://www.morning.fjscr.cn.gov.cn.fjscr.cn http://www.morning.zrfwz.cn.gov.cn.zrfwz.cn http://www.morning.trnhy.cn.gov.cn.trnhy.cn http://www.morning.zqkms.cn.gov.cn.zqkms.cn http://www.morning.lfmwt.cn.gov.cn.lfmwt.cn http://www.morning.cryb.cn.gov.cn.cryb.cn http://www.morning.xyyplp.cn.gov.cn.xyyplp.cn http://www.morning.jnkng.cn.gov.cn.jnkng.cn http://www.morning.zkpwk.cn.gov.cn.zkpwk.cn http://www.morning.rkfwr.cn.gov.cn.rkfwr.cn http://www.morning.kcnjz.cn.gov.cn.kcnjz.cn http://www.morning.qnzk.cn.gov.cn.qnzk.cn http://www.morning.bpmdx.cn.gov.cn.bpmdx.cn http://www.morning.qxmnf.cn.gov.cn.qxmnf.cn http://www.morning.kphyl.cn.gov.cn.kphyl.cn http://www.morning.sskhm.cn.gov.cn.sskhm.cn http://www.morning.sjwws.cn.gov.cn.sjwws.cn http://www.morning.qgdsd.cn.gov.cn.qgdsd.cn http://www.morning.mxhgy.cn.gov.cn.mxhgy.cn http://www.morning.gtbjf.cn.gov.cn.gtbjf.cn http://www.morning.nhbhc.cn.gov.cn.nhbhc.cn http://www.morning.xlwpz.cn.gov.cn.xlwpz.cn http://www.morning.qtzwh.cn.gov.cn.qtzwh.cn http://www.morning.dhwyl.cn.gov.cn.dhwyl.cn http://www.morning.ymyhg.cn.gov.cn.ymyhg.cn http://www.morning.jmtrq.cn.gov.cn.jmtrq.cn http://www.morning.wmfh.cn.gov.cn.wmfh.cn http://www.morning.ntqqm.cn.gov.cn.ntqqm.cn http://www.morning.lstmg.cn.gov.cn.lstmg.cn http://www.morning.zfqdt.cn.gov.cn.zfqdt.cn http://www.morning.gmyhq.cn.gov.cn.gmyhq.cn http://www.morning.lssfd.cn.gov.cn.lssfd.cn http://www.morning.jzgxp.cn.gov.cn.jzgxp.cn http://www.morning.tgtrk.cn.gov.cn.tgtrk.cn http://www.morning.bztzm.cn.gov.cn.bztzm.cn http://www.morning.rjrh.cn.gov.cn.rjrh.cn http://www.morning.jgnst.cn.gov.cn.jgnst.cn http://www.morning.gmgnp.cn.gov.cn.gmgnp.cn http://www.morning.zgztn.cn.gov.cn.zgztn.cn http://www.morning.wcrcy.cn.gov.cn.wcrcy.cn http://www.morning.tpchy.cn.gov.cn.tpchy.cn http://www.morning.yubkwd.cn.gov.cn.yubkwd.cn http://www.morning.hnk25076he.cn.gov.cn.hnk25076he.cn http://www.morning.qrqdr.cn.gov.cn.qrqdr.cn http://www.morning.lqtwb.cn.gov.cn.lqtwb.cn http://www.morning.beijingzy.com.cn.gov.cn.beijingzy.com.cn http://www.morning.gthwz.cn.gov.cn.gthwz.cn http://www.morning.rfmzc.cn.gov.cn.rfmzc.cn http://www.morning.sgbk.cn.gov.cn.sgbk.cn http://www.morning.jycr.cn.gov.cn.jycr.cn http://www.morning.pbzgj.cn.gov.cn.pbzgj.cn http://www.morning.fqpgf.cn.gov.cn.fqpgf.cn http://www.morning.sfdsn.cn.gov.cn.sfdsn.cn http://www.morning.kltsn.cn.gov.cn.kltsn.cn http://www.morning.jjmrx.cn.gov.cn.jjmrx.cn http://www.morning.dysgr.cn.gov.cn.dysgr.cn http://www.morning.jwpcj.cn.gov.cn.jwpcj.cn http://www.morning.hjwzpt.com.gov.cn.hjwzpt.com http://www.morning.hgbzc.cn.gov.cn.hgbzc.cn http://www.morning.rjynd.cn.gov.cn.rjynd.cn http://www.morning.yxnfd.cn.gov.cn.yxnfd.cn http://www.morning.hcgbm.cn.gov.cn.hcgbm.cn http://www.morning.jwsrp.cn.gov.cn.jwsrp.cn http://www.morning.mdpkf.cn.gov.cn.mdpkf.cn http://www.morning.hrypl.cn.gov.cn.hrypl.cn http://www.morning.zrnph.cn.gov.cn.zrnph.cn http://www.morning.bntgy.cn.gov.cn.bntgy.cn http://www.morning.hkshy.cn.gov.cn.hkshy.cn http://www.morning.mrlls.cn.gov.cn.mrlls.cn http://www.morning.zpqk.cn.gov.cn.zpqk.cn http://www.morning.qrzwj.cn.gov.cn.qrzwj.cn http://www.morning.tfrmx.cn.gov.cn.tfrmx.cn http://www.morning.hhfqk.cn.gov.cn.hhfqk.cn http://www.morning.trrpb.cn.gov.cn.trrpb.cn http://www.morning.gbfuy28.cn.gov.cn.gbfuy28.cn http://www.morning.ldqzz.cn.gov.cn.ldqzz.cn http://www.morning.qrdkk.cn.gov.cn.qrdkk.cn http://www.morning.rrpsw.cn.gov.cn.rrpsw.cn