Lambda用法
- 占位符
| package Test; |
| |
| |
| import com.alibaba.fastjson.JSON; |
| import lombok.Data; |
| |
| import java.util.ArrayList; |
| import java.util.Collections; |
| import java.util.List; |
| import java.util.Map; |
| import java.util.stream.Collectors; |
| |
| public class Test { |
| |
| public static void main(String[] args) { |
| |
| |
| Student Ming = new Student("小明", "男", "1"); |
| Student Red = new Student("小红", "女", "1"); |
| Student Gang = new Student("小刚", "男", "2"); |
| Student Bai = new Student("小白", "男", "2"); |
| Student Lan = new Student("小蓝", "男", "3"); |
| List<Student> list = new ArrayList<>(); |
| Collections.addAll(list, Ming, Red, Gang, Bai, Lan); |
| System.out.println(JSON.toJSON(list) + "\n"); |
| |
| |
| |
| list.stream().collect(Collectors.groupingBy(Student::getClazz)).forEach((k, v) -> System.out.println(JSON.toJSON(k + ": " + v))); |
| |
| |
| |
| |
| System.out.println(); |
| |
| |
| List<Student> collect = list.stream().filter(student -> !student.getClazz().equals("3")).collect(Collectors.toList()); |
| collect.removeIf(k -> k.getClazz().equals("2")); |
| |
| System.out.println(JSON.toJSON(collect) + "\n"); |
| |
| |
| |
| |
| Map<String, String> storeMap = list.stream().collect(Collectors.toMap(student -> {return student.getName();}, Student::getClazz)); |
| storeMap.forEach((k,v) -> System.out.println("{key=" + k + ", value=" + v + "}")); |
| |
| } |
| |
| @Data |
| static class Student { |
| private String Name; |
| private String Sex; |
| private String Clazz; |
| |
| Student(String name, String sex, String clazz) { |
| Name = name; |
| Sex = sex; |
| Clazz = clazz; |
| } |
| } |
| } |
- 改变元素
| public class T { |
| public static void main(String[] args) { |
| |
| DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); |
| |
| Student student01 = new Student().setId(1).setName("张三").setDate(String.valueOf(new Date())); |
| Student student02 = new Student().setId(2).setName("历史").setDate(new Date().toString()); |
| |
| List<Student> list = Lists.newArrayList(); |
| Collections.addAll(list, student01, student02); |
| |
| |
| System.out.println("数量:" + list.stream().map(Student::getId).distinct().count()); |
| |
| System.out.println("转Map:" + list.stream().collect(Collectors.toMap(Student::getId, Student::getName))); |
| |
| |
| System.out.println("改变原集合数据格式为:" + list.stream().map(item -> new Student().setId(item.getId() + 1).setName("SpringBoot").setDate(dateFormat.format(new Date()))).collect(Collectors.toList())); |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~