首页 > 代码库 > Java8 Lambda代码备份
Java8 Lambda代码备份
简单研究了一下,贴出来,相当于笔记
import java.lang.reflect.*; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import com.google.gson.Gson; public class Hello { public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { try { // Java中Lambda表达式 List<Student> list = new ArrayList<Student>(); list.add(new Student("zhangsan", 20, "2")); list.add(new Student("lisi", 22, "2")); list.add(new Student("zhangjie", 25, "3")); list.add(new Student("zhangjie", 40, "3")); // 循环赋值,增加2岁 list.forEach(item -> item.setAge(item.getAge() + 2)); // 循环输出年龄 list.forEach(item -> System.out.println(item.getAge())); // 总数、最大值、最小值 int ages = list.stream().mapToInt(f -> f.getAge()).sum(); int maxAge = list.stream().mapToInt(f -> f.getAge()).max().getAsInt(); System.err.println("总年龄是:" + ages); System.err.println("最大年龄是:" + maxAge); // 分组 list.stream().collect(Collectors.groupingBy(Student::getName, Collectors.toList()))// .forEach((name, fooListByName) -> System.out.println(name + " " + new Gson().toJson(fooListByName))); list.stream().collect(Collectors.groupingBy(Student::getName, Collectors.counting()))// .forEach((name, count) -> System.out.println(name + " " + count)); list.stream().collect(Collectors.groupingBy(Student::getName, Collectors.toList()))// .forEach((name, ls) -> System.out.println("姓名:" + name + ",最大年龄" + ls.stream().mapToInt(f -> f.getAge()).max().getAsInt())); } finally { } } }
Java8 Lambda代码备份
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。