Java8 Lambda代碼備份
阿新 • • 發佈:2017-07-07
ring collector class student ati tor getname int() log
簡單研究了一下,貼出來,相當於筆記
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代碼備份