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

Java中各种数据结构如何使用stream流

1. List

假设你有一个List<String>,你可以使用Stream来过滤、映射、排序等。

List<String> list = Arrays.asList("apple", "banana", "cherry", "date");  
  
// 过滤操作  
List<String> filteredList = list.stream()  
    .filter(s -> s.startsWith("a"))  
    .collect(Collectors.toList());  
  
// 映射操作  
List<Integer> lengths = list.stream()  
    .map(String::length)  
    .collect(Collectors.toList());  

  
// 排序操作  
List<String> sortedList = list.stream()  
    .sorted()  
    .collect(Collectors.toList());

2. Set

虽然Set不保证元素的顺序,但你可以使用Stream API对其中的元素进行操作。

Set<String> set = new HashSet<>(Arrays.asList("apple", "banana", "cherry"));  
  
// 过滤并收集为List  
List<String> filteredList = set.stream()  
    .filter(s -> s.startsWith("a"))  
    .collect(Collectors.toList());  
  
// 查找最长字符串  
Optional<String> longestString = set.stream()  
    .max(Comparator.comparing(String::length));

3. Map

对于Map,你可以对流中的键(keys)、值(values)或键值对(entries)进行操作。

Map<String, Integer> map = new HashMap<>();  
map.put("apple", 100);  
map.put("banana", 200);  
map.put("cherry", 150);  
  
// 对值进行操作,查找最大值  
Optional<Integer> maxValue = map.values().stream()  
    .max(Integer::compareTo);  
  
// 对键值对进行操作  
// 获取value大于100的key列表
List<String> keysWithValuesOver100 = map.entrySet().stream()  
    .filter(e -> e.getValue() > 100)  
    .map(Map.Entry::getKey)  
    .collect(Collectors.toList());

4. Array

数组也可以通过Stream API来处理,但需要先将其转换为流。

String[] array = {"apple", "banana", "cherry"};  
  
// 转换为流,然后进行操作  
List<String> filteredList = Arrays.stream(array)  
    .filter(s -> s.startsWith("a"))  
    .collect(Collectors.toList());

 

 


http://www.kler.cn/news/303643.html

相关文章:

  • Xcode报错:Return from initializer without initializing all stored properties
  • Java-乐观锁和悲观锁的理解及实现方式
  • Android 亮度范围定制
  • uniapp tabBar不显示
  • 利用python处理线性规划问题
  • 宠物毛发对人体有什么危害?宠物空气净化器小米、希喂、352对比实测
  • 电信网络携手大模型:AI赋能网络运维的新范式
  • 合宙Air201资产定位模组LuatOS:开机容易关机难?PWRKEY控制来帮忙
  • 【STM8】STM8固件库的坑(GPIO_ReadInputDataBit)
  • 如何编译OpenHarmony SDK API
  • ‘“node“‘ �����ڲ����ⲿ���Ҳ���ǿ����еij��� ���������ļ���
  • 体育场座位【python实现】
  • 谷歌-BERT-“bert-base-chinese ”
  • 网络运维故障处理
  • Java | Leetcode Java题解之第396题旋转函数
  • 开源项目低代码表单FormCreate中通过接口加载远程数据选项
  • MySQL:undo log
  • 吴恩达大神神作经典珍藏版:《LLM大模型通关手册》面面俱到太全了!
  • Ubuntu 下载软件包时,提示 但是它将不会被安装E: 无法修正错误,因为您要求某些软件包保持现状,就是它们破坏了软件包间的依赖关系。
  • 【网络安全 | 甲方建设】SaaS平台、Jira工具及Jenkins服务器
  • LeetCode之字典树
  • SpringBoot3与SpringBoot2的区别
  • 内存魔术师:精通内存函数的艺术
  • 如何划分类/单一职权原则SRP
  • java重点学习-线程的并发安全(2)
  • 甘特图介绍
  • 解锁生活密码,AI答案之书解决复杂难题
  • 提取蛋白质复合体结构中组装体的变换矩阵
  • gitlab配置统一前缀路径源码版
  • 论文复现--基于LeNet网络结构的数字识别