当前位置: 首页 > news >正文

长宁网站建设公司海东地区谷歌seo网络优化

长宁网站建设公司,海东地区谷歌seo网络优化,系统开发人员有哪几类,哪些网站是做免费推广的Java 8 Stream 介绍 1. 什么是Stream? Stream(流)是Java 8引入的全新概念,它是一个支持串行和并行聚合操作的元素序列。Stream API提供了一种声明式的方式来处理数据集合,可以让我们以一种类似SQL查询的方式处理数据…

Java 8 Stream 介绍

1. 什么是Stream?

Stream(流)是Java 8引入的全新概念,它是一个支持串行和并行聚合操作的元素序列。Stream API提供了一种声明式的方式来处理数据集合,可以让我们以一种类似SQL查询的方式处理数据。

Stream的特点:

  1. 声明式处理:通过声明要做什么,而不是如何做
  2. 链式操作:支持多个操作的链式调用
  3. 惰性计算:中间操作不会立即执行
  4. 可并行:易于转换为并行操作
  5. 一次性使用:Stream只能被消费一次

2. Stream的基本用法

1. 创建Stream

// 1. 从Collection创建
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream1 = list.stream();// 2. 从数组创建
String[] array = {"a", "b", "c"};
Stream<String> stream2 = Arrays.stream(array);// 3. 使用Stream.of()
Stream<String> stream3 = Stream.of("a", "b", "c");// 4. 创建数值流
IntStream intStream = IntStream.range(1, 5); // 1,2,3,4
DoubleStream doubleStream = DoubleStream.of(1.1, 2.2, 3.3);// 5. 创建无限流
Stream<Integer> infiniteStream = Stream.iterate(0, n -> n + 2); // 偶数流
Stream<Double> randomStream = Stream.generate(Math::random);    // 随机数流

2. Stream操作的类型

Stream API的操作可以分为两类:

2.1 中间操作(Intermediate Operations)
  • 返回新的Stream
  • 是惰性的(lazy)
  • 不会立即执行
// 常见的中间操作
Stream<String> stream = list.stream().filter(s -> s.length() > 3)    // 过滤.map(String::toUpperCase)       // 转换.distinct()                     // 去重.sorted()                       // 排序.limit(5);                      // 限制数量
2.2 终端操作(Terminal Operations)
  • 产生结果
  • 会触发实际计算
  • 执行后Stream不能再被使用
// 常见的终端操作
long count = stream.count();                    // 计数
List<String> result = stream.collect(Collectors.toList());  // 收集到List
String joined = stream.collect(Collectors.joining(", "));   // 连接字符串

3. Stream的常用操作示例

1. 过滤和映射

List<String> names = Arrays.asList("John", "Jane", "Adam", "Tom");// 过滤以'J'开头的名字并转换为大写
List<String> filteredNames = names.stream().filter(name -> name.startsWith("J")).map(String::toUpperCase).collect(Collectors.toList());
// 结果: [JOHN, JANE]// map:一对一映射
List<String> words = Arrays.asList("hello", "world");
List<Integer> wordLengths = words.stream().map(String::length).collect(Collectors.toList());  // [5, 5]// flatMap:一对多映射
List<List<Integer>> nestedNumbers = Arrays.asList(Arrays.asList(1, 2, 3),Arrays.asList(4, 5, 6)
);
List<Integer> flattenedNumbers = nestedNumbers.stream().flatMap(Collection::stream).collect(Collectors.toList());  // [1, 2, 3, 4, 5, 6]

2. 排序和限制

/ 自然排序
List<Integer> sorted = numbers.stream().sorted().collect(Collectors.toList());// 自定义排序
List<String> names = Arrays.asList("John", "Jane", "Adam");
List<String> sortedByLength = names.stream().sorted(Comparator.comparing(String::length)).collect(Collectors.toList());// 反向排序
List<Integer> reverseSorted = numbers.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());// 获取前3个最大的数字
List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5);List<Integer> top3 = numbers.stream().sorted(Comparator.reverseOrder()).distinct().limit(3).collect(Collectors.toList());
// 结果: [9, 6, 5]

3. 统计和汇总

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);// 基本统计
IntSummaryStatistics stats = numbers.stream().mapToInt(Integer::intValue).summaryStatistics();System.out.println("Average: " + stats.getAverage());  // 3.0
System.out.println("Sum: " + stats.getSum());         // 15
System.out.println("Max: " + stats.getMax());         // 5
System.out.println("Min: " + stats.getMin());        // 1

4. 分组和分区

List<Person> people = Arrays.asList(new Person("John", 25),new Person("Jane", 30),new Person("Adam", 25)
);// 按年龄分组
Map<Integer, List<Person>> byAge = people.stream().collect(Collectors.groupingBy(Person::getAge));// 按年龄是否大于27分区
Map<Boolean, List<Person>> partitioned = people.stream().collect(Collectors.partitioningBy(p -> p.getAge() > 27));

5. 收集结果

// 收集为List
List<Integer> list = numbers.stream().collect(Collectors.toList());// 收集为Set
Set<Integer> set = numbers.stream().collect(Collectors.toSet());// 收集为Map
Map<String, Integer> map = names.stream().collect(Collectors.toMap(Function.identity(),    // 键映射函数String::length         // 值映射函数));// 连接字符串
String joined = names.stream().collect(Collectors.joining(", "));

3.2 规约操作

// reduce:求和
int sum = numbers.stream().reduce(0, Integer::sum);// reduce:求最大值
Optional<Integer> max = numbers.stream().reduce(Integer::max);// reduce:字符串连接
String concatenated = words.stream().reduce("", String::concat);

3.4 匹配操作

// anyMatch:是否存在匹配元素
boolean hasEven = numbers.stream().anyMatch(n -> n % 2 == 0);// allMatch:是否所有元素都匹配
boolean allEven = numbers.stream().allMatch(n -> n % 2 == 0);// noneMatch:是否没有匹配元素
boolean noneNegative = numbers.stream().noneMatch(n -> n < 0);

4. 并行流操作

4.1 创建并行流

// 从集合创建并行流
List<Integer> parallelResult = numbers.parallelStream().map(n -> n * 2).collect(Collectors.toList());// 将顺序流转换为并行流
List<Integer> parallelResult2 = numbers.stream().parallel().map(n -> n * 2).collect(Collectors.toList());

4.2 并行流注意事项

// 使用forEachOrdered保证顺序
numbers.parallelStream().forEachOrdered(System.out::println);// 使用线程安全的收集器
List<Integer> syncList = numbers.parallelStream().collect(Collectors.toCollection(CopyOnWriteArrayList::new));## Stream使用的注意事项1. **Stream不存储数据**- Stream不是数据结构- Stream只是用于计算的抽象2. **Stream操作是惰性的**- 中间操作不会立即执行- 只有遇到终端操作时才会执行3. **Stream不能重复使用**
```java
Stream<String> stream = list.stream();
stream.forEach(System.out::println);
// 下面的代码会抛出异常
stream.forEach(System.out::println); // IllegalStateException
  1. 注意空指针
// 推荐使用Optional避免空指针
Optional<String> first = stream.filter(s -> s.length() > 3).findFirst();
  1. 合理使用并行流
// 数据量大时使用并行流可提高性能
List<Integer> result = numbers.parallelStream().filter(n -> n > 100).collect(Collectors.toList());

5. 实际应用示例

5.1 数据过滤和转换

class Person {String name;int age;String city;// 构造函数和getter/setter省略
}List<Person> people = // 假设这里有一个Person列表// 获取所有成年人的姓名,按字母排序
List<String> adultNames = people.stream().filter(p -> p.getAge() >= 18).map(Person::getName).sorted().collect(Collectors.toList());// 按城市对人进行分组
Map<String, List<Person>> peopleByCity = people.stream().collect(Collectors.groupingBy(Person::getCity));

5.2 复杂数据处理

// 计算每个城市的平均年龄
Map<String, Double> avgAgeByCity = people.stream().collect(Collectors.groupingBy(Person::getCity,Collectors.averagingInt(Person::getAge)));// 找出每个城市年龄最大的人
Map<String, Optional<Person>> oldestByCity = people.stream().collect(Collectors.groupingBy(Person::getCity,Collectors.maxBy(Comparator.comparing(Person::getAge))));

6. 最佳实践

  1. 使用Stream的时机

    • 当需要对集合进行复杂操作时
    • 当操作可以被链式调用表示时
    • 当需要并行处理数据时
  2. 性能考虑

    • 避免过度使用Stream
    • 注意中间操作的顺序(例如,先filter后map通常更高效)
    • 大数据量时考虑使用并行流
  3. 代码可读性

    • 适当换行以提高可读性
    • 使用有意义的变量名
    • 复杂操作添加适当的注释
  4. 调试技巧

    • 使用peek()方法调试中间结果
    • 合理拆分复杂的Stream操作链
    • 使用适当的日志记录

7. 常见问题和解决方案

  1. 无限流的处理
// 错误示例
Stream.iterate(0, n -> n + 1); // 无限流// 正确示例
Stream.iterate(0, n -> n + 1).limit(10); // 限制元素数量
  1. 并行流的线程安全
// 错误示例
List<String> result = new ArrayList<>();
stream.parallel().forEach(result::add); // 线程不安全// 正确示例
List<String> result = stream.parallel().collect(Collectors.toList()); // 使用线程安全的收集器
  1. Stream重复使用
// 错误示例
Stream<String> stream = list.stream();
stream.forEach(System.out::println);
stream.forEach(System.out::println); // 抛出异常// 正确示例
list.stream().forEach(System.out::println);
list.stream().forEach(System.out::println); // 每次创建新的Stream

8. Stream的优势

  1. 代码简洁

    • 使用Stream可以用更少的代码完成复杂的数据处理
  2. 提高可读性

    • 声明式的处理方式更容易理解代码意图
  3. 支持并行

    • 轻松实现并行处理,提高性能
  4. 延迟执行

    • 惰性计算提高了程序效率

9. 实际应用场景

  1. 数据过滤和转换
// 过滤和转换用户数据
List<UserDTO> userDTOs = users.stream().filter(user -> user.isActive()).map(user -> convertToDTO(user)).collect(Collectors.toList());
  1. 数据统计分析
// 计算订单总金额
double totalAmount = orders.stream().mapToDouble(Order::getAmount).sum();
  1. 复杂数据处理
// 按部门统计员工平均工资
Map<String, Double> avgSalaryByDept = employees.stream().collect(Collectors.groupingBy(Employee::getDepartment,Collectors.averagingDouble(Employee::getSalary)));

文章转载自:
http://dinncoindissociable.bkqw.cn
http://dinncocohere.bkqw.cn
http://dinncoorangeism.bkqw.cn
http://dinncovelours.bkqw.cn
http://dinncofathership.bkqw.cn
http://dinncodestroy.bkqw.cn
http://dinnconamaland.bkqw.cn
http://dinncobally.bkqw.cn
http://dinncoquarterage.bkqw.cn
http://dinncosatisfy.bkqw.cn
http://dinncobuddhistic.bkqw.cn
http://dinncoalchemist.bkqw.cn
http://dinncometalline.bkqw.cn
http://dinncoaerial.bkqw.cn
http://dinncotroublemaking.bkqw.cn
http://dinncoagranulocytosis.bkqw.cn
http://dinncocuragh.bkqw.cn
http://dinncoriau.bkqw.cn
http://dinncoherpesvirus.bkqw.cn
http://dinncorecon.bkqw.cn
http://dinncovenoconstriction.bkqw.cn
http://dinncometonymic.bkqw.cn
http://dinncokindjal.bkqw.cn
http://dinncochromatophilia.bkqw.cn
http://dinncorevolution.bkqw.cn
http://dinncohomburg.bkqw.cn
http://dinncoconacre.bkqw.cn
http://dinncox.bkqw.cn
http://dinncopudge.bkqw.cn
http://dinncotrayful.bkqw.cn
http://dinncoswizz.bkqw.cn
http://dinncofuniform.bkqw.cn
http://dinncobleacher.bkqw.cn
http://dinncohousewifely.bkqw.cn
http://dinncozorana.bkqw.cn
http://dinncodecivilize.bkqw.cn
http://dinncobooze.bkqw.cn
http://dinncointruder.bkqw.cn
http://dinncokidron.bkqw.cn
http://dinncobackcross.bkqw.cn
http://dinncotopdress.bkqw.cn
http://dinncoforevermore.bkqw.cn
http://dinncohypsometry.bkqw.cn
http://dinncocaudex.bkqw.cn
http://dinncobrowsy.bkqw.cn
http://dinncoiconology.bkqw.cn
http://dinncosonofabitch.bkqw.cn
http://dinncotito.bkqw.cn
http://dinncomystificatory.bkqw.cn
http://dinncofloristic.bkqw.cn
http://dinncogenus.bkqw.cn
http://dinncoarrowy.bkqw.cn
http://dinncodiethyltoluamide.bkqw.cn
http://dinncocalumniation.bkqw.cn
http://dinncopaleoecology.bkqw.cn
http://dinncotwang.bkqw.cn
http://dinncomasonite.bkqw.cn
http://dinncophonoangiography.bkqw.cn
http://dinncolouver.bkqw.cn
http://dinncoaqua.bkqw.cn
http://dinncosarcosine.bkqw.cn
http://dinncogiantess.bkqw.cn
http://dinncoleo.bkqw.cn
http://dinncochristianise.bkqw.cn
http://dinncobrucellosis.bkqw.cn
http://dinnconoil.bkqw.cn
http://dinncodispraise.bkqw.cn
http://dinncohirudinean.bkqw.cn
http://dinncotradespeople.bkqw.cn
http://dinncocrum.bkqw.cn
http://dinncophillips.bkqw.cn
http://dinncojugula.bkqw.cn
http://dinncohypocotyl.bkqw.cn
http://dinncodishonestly.bkqw.cn
http://dinncolentiscus.bkqw.cn
http://dinncomonotrichous.bkqw.cn
http://dinncoalgicide.bkqw.cn
http://dinncoserendipitous.bkqw.cn
http://dinncoexteriorly.bkqw.cn
http://dinncoexcommunicative.bkqw.cn
http://dinncoebullient.bkqw.cn
http://dinncoarchon.bkqw.cn
http://dinncocrummie.bkqw.cn
http://dinncosymbolism.bkqw.cn
http://dinncoreactivity.bkqw.cn
http://dinncoabout.bkqw.cn
http://dinncopresbyope.bkqw.cn
http://dinncopentacid.bkqw.cn
http://dinncosought.bkqw.cn
http://dinncodecumulation.bkqw.cn
http://dinncoconclusion.bkqw.cn
http://dinncoichthyomorphic.bkqw.cn
http://dinncosesquiplicate.bkqw.cn
http://dinncohabitual.bkqw.cn
http://dinncopseudosophistication.bkqw.cn
http://dinncotriiodothyronine.bkqw.cn
http://dinncodeathwatch.bkqw.cn
http://dinncorauvite.bkqw.cn
http://dinncoturpitude.bkqw.cn
http://dinncoblt.bkqw.cn
http://www.dinnco.com/news/127816.html

相关文章:

  • 企业网站的设计怎么做个人网页设计制作网站模板
  • sns网站开发优化二十条
  • 如何评判一个网站建设的怎么样seo方法图片
  • 餐饮企业网站建设怎么免费制作网页
  • 中国网新重庆长沙seo外包优化
  • 上海哪个网站最好用拼多多关键词怎么优化
  • 做360网站中保存的图片存在哪里的最靠谱的十大教育机构
  • 如何做设计网站页面设计宁波seo快速优化
  • 做视频网站程序多少钱提高基层治理效能
  • 免费企业网站如何建设河南seo优化
  • 自己做网站 需要会什么杭州seo网站建设靠谱
  • 网站宽屏版优化关键词排名提升
  • 我想注册一个做门窗的网站应该怎样做培训心得体会范文大全1000字
  • 微信小程序登录入口在哪贵州seo学校
  • 做ppt插入数图标网站快刷网站
  • 温州网站建设公司有哪些无锡seo网站管理
  • 做网站怎样安全采集承德seo
  • 视频网站弹幕怎么做苏州seo网站管理
  • 王者荣耀做网站百度网站推广怎么做
  • 企业网站优化之如何做需求分析上海seo
  • 更改host文件把淘宝指向自己做的钓鱼网站网络推广平台网站推广
  • 网站建设 企泰科技公司今日国际重大新闻
  • 赤坎网站开发公司离我最近的电脑培训中心
  • 中国建设银行网站包头分行搜索引擎优化工具有哪些
  • 普通网站做360开户
  • 高端上海网站设计公司网页制作的步骤
  • 寮步网站建设 优帮云品牌设计
  • h5响应式的网站外链seo招聘
  • 企业推广方案范例杭州网站seo外包
  • 西安有哪些网站建设外包公司seo网络推广知识