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

Java 集合 示例

Collection

package com.example.demo1;import java.util.ArrayList;
import java.util.Iterator;
import java.util.Collection;public class CollectionDemo {public static void main(String[] args) {// ======================================// 1. 初始化Collection集合(使用ArrayList实现)// ======================================Collection<String> fruits = new ArrayList<>();// ======================================// 2. 演示Collection常用方法// ======================================// boolean add(E e):添加元素fruits.add("苹果");fruits.add("香蕉");fruits.add("橙子");System.out.println("添加后集合:" + fruits);  // 输出:[苹果, 香蕉, 橙子]// boolean contains(Object o):判断是否存在System.out.println("是否包含香蕉:" + fruits.contains("香蕉"));  // 输出:true// int size():集合长度System.out.println("当前集合大小:" + fruits.size());  // 输出:3// boolean remove(Object o):移除指定元素System.out.println("移除苹果结果:" + fruits.remove("苹果"));  // 输出:trueSystem.out.println("移除后集合:" + fruits);  // 输出:[香蕉, 橙子]// boolean isEmpty():判断是否为空System.out.println("集合是否为空:" + fruits.isEmpty());  // 输出:false// boolean removeIf(Predicate):根据条件移除(需要Java 8+)// 示例:移除所有包含"橙"字的元素boolean removed = fruits.removeIf(fruit -> fruit.contains("橙"));System.out.println("条件移除结果:" + removed);  // 输出:trueSystem.out.println("条件移除后集合:" + fruits);  // 输出:[香蕉]// void clear():清空集合fruits.clear();System.out.println("清空后集合:" + fruits);  // 输出:[]// ======================================// 3. 重新填充数据用于遍历演示// ======================================fruits.add("葡萄");fruits.add("草莓");fruits.add("芒果");// ======================================// 4. 迭代器遍历(Iterator)// ======================================Iterator<String> iterator = fruits.iterator();System.out.println("\n迭代器遍历:");while (iterator.hasNext()) {  // 判断是否有下一个元素String fruit = iterator.next();  // 获取当前元素并移动指针System.out.print(fruit + " ");   // 输出:葡萄 草莓 芒果 // 示例:用迭代器删除元素(安全操作)if ("草莓".equals(fruit)) {iterator.remove();  // 删除当前指向的元素}}System.out.println("\n迭代器删除后集合:" + fruits);  // 输出:[葡萄, 芒果]// ======================================// 5. 增强for循环(for-each)// ======================================System.out.println("\n增强for循环遍历:");for (String fruit : fruits) {  // 自动遍历集合中每个元素System.out.print(fruit + " ");  // 输出:葡萄 芒果 }// ======================================// 6. Lambda表达式的使用(结合Collection的forEach)// ======================================System.out.println("\nLambda表达式遍历:");fruits.forEach(fruit -> {  // Lambda表达式替代匿名内部类System.out.print(fruit + " ");  // 输出:葡萄 芒果 });// 更简洁的Lambda写法(方法引用)// fruits.forEach(System.out::print);}
}

能使用 Lambda 表达式,需满足以下条件

1. 目标类型为函数式接口

Lambda 表达式只能用于函数式接口的上下文。函数式接口指的是仅包含一个抽象方法的接口。

@FunctionalInterface
public interface Predicate<T> {boolean test(T t);
}

Predicate<T> 被 @FunctionalInterface 注解标记,表明它是函数式接口,且只有一个抽象方法 test(T t)。所以,removeIf 方法的参数位置可使用 Lambda 表达式。

2. 参数类型兼容

Lambda 表达式的参数类型要和函数式接口中抽象方法的参数类型兼容。Predicate<String> 里 test 方法的参数类型为 String,因此 Lambda 表达式的参数类型也得是 String,像 fruit -> fruit.contains("橙") 中,fruit 就被推断为 String 类型。

3. 返回值类型匹配

Lambda 表达式的返回值类型要和函数式接口中抽象方法的返回值类型一致。Predicate<String> 里 test 方法的返回值类型是 boolean,所以 fruit -> fruit.contains("橙") 的返回值也得是 boolean 类型,contains 方法恰好返回 boolean 类型的值,满足要求。

不用Lambda 表达式的写法

// ... 已有代码 ...
// boolean removeIf(Predicate):根据条件移除(需要Java 8+)
// 示例:移除所有包含"橙"字的元素
boolean removed = fruits.removeIf(new java.util.function.Predicate<String>() {@Overridepublic boolean test(String fruit) {return fruit.contains("橙");}
});
System.out.println("条件移除结果:" + removed);  // 输出:true
System.out.println("条件移除后集合:" + fruits);  // 输出:[香蕉]
// ... 已有代码 ...


文章转载自:
http://achinese.bdypl.cn
http://bolton.bdypl.cn
http://aiche.bdypl.cn
http://acidulate.bdypl.cn
http://abutment.bdypl.cn
http://appulse.bdypl.cn
http://antirheumatic.bdypl.cn
http://borderism.bdypl.cn
http://broadtail.bdypl.cn
http://chesterfield.bdypl.cn
http://chasmy.bdypl.cn
http://carrageen.bdypl.cn
http://antineuritic.bdypl.cn
http://adm.bdypl.cn
http://amd.bdypl.cn
http://auditive.bdypl.cn
http://blurb.bdypl.cn
http://caernarvon.bdypl.cn
http://amidohydrolase.bdypl.cn
http://aluminise.bdypl.cn
http://arcograph.bdypl.cn
http://apocrypha.bdypl.cn
http://appreciator.bdypl.cn
http://befell.bdypl.cn
http://anew.bdypl.cn
http://attainable.bdypl.cn
http://buddhist.bdypl.cn
http://afternooner.bdypl.cn
http://biassed.bdypl.cn
http://bern.bdypl.cn
http://www.dtcms.com/a/281250.html

相关文章:

  • python学智能算法(二十)|SVM基础概念-感知机算法及代码
  • SAP把运费加入到物料成本估算
  • 使用 Aerich 进行 FastAPI 数据库迁移指南
  • redis红锁
  • GitHub 上 Star 数量前 8 的开源 Web 应用项目
  • 如何解决pip安装报错ModuleNotFoundError: No module named ‘pandas’问题
  • centos8集群部署etcd
  • 【12】MFC入门到精通——MFC 消息对话框 MessageBox()和AfxMessageBox() 解析 示例 及 应用实例
  • 【目标追踪】MUTR3D: A Multi-camera Tracking Framework via 3D-to-2D Queries
  • MongoDB数据问题说明
  • css-css执行的三种方式和css选择器
  • AS32X601 系列 MCU 硬件最小系统设计与调试方案探析
  • Agentic AI 的威胁与缓解措施
  • 如何快速有效地在WordPress中添加Instagram动态
  • 【PTA数据结构 | C语言版】前序遍历二叉树
  • 零基础入门物联网-远程门禁开关:代码调试
  • 过滤数组中null、undefined、‘‘、等非真内容
  • AAAI-2025 | 同济大学面向嘈杂环境的音频视觉导航!BeDAViN:大规模音频-视觉数据集与多声源架构研究
  • OpenCSG QA:您的国产大模型与 Agent 管理平台
  • 变更缓冲池简介
  • 19.1 单元测试框架
  • ssm学习笔记day08mybatis
  • ESP32轻松实现UDP无线通信
  • 使用python的pillow模块将图片转化为灰度图,获取值和修改值
  • 雷军的 IP 革命:人格化力量如何重塑商业规则|创客匠人
  • uniapp微信小程序弹窗
  • 《汇编语言:基于X86处理器》第8章 高级过程(1)
  • 被人工智能激活的哲学
  • 短剧小程序的「技术革命」:从「粗放生长」到「精准运营」
  • Windows内核对象