三部分
一些参数
一个箭头
一段代码
格式
(参数列表) -> (重写方法的代码)() :—> 没有参数就空着,有参数就写参数,多个参数都好分割-> :—> 传递的意思{} :—>重写抽象方法的方法体 2、Lambda表达式
Lambda表达式是可推导,可省略可省略的内容
(参数列表): 括号参数列表的数据类型可以省略不写(参数列表): 括号的参数如果只有一个,那么类型和()都可以省略(一些代码): 如果{}中的代码只有一行,无论是否有返回值,都可以省略({},return,分号)要省略{},return,分号必须一起省略 3、Lambda表达式使用前提
使用Lambda必须要有接口,且要求接口中有且仅有一个抽象方法
比如通过new Tread创建线程时使用。
二、使用 1、遍历(forEach)//Map对象 Map2、遍历操作(map)map= new HashMap<>(); map.forEach((k,v)->{ // 打印键 System.out.println(k); // 打印值 System.out.println(v); }); //list对象 List list = new ArrayList(); list.forEach((l)->{ System.out.println(l.getId()); System.out.println(l.getName()); }); //Set对象 Set set = new HashSet<>(); set.forEach((s)->{ System.out.println(s.getId()); System.out.println(s.getName()); });
List3、条件过滤ids = new ArrayList<>(); List collect = ids.stream().map(a -> a + "123").collect(Collectors.toList());
//对象数据 List4、排序list = new ArrayList<>(); List collect = list.stream().filter(user -> !"张三".equals(user.getName())) .collect(Collectors.toList()); //单一数组 List ids = new ArrayList<>(); List collect = ids.stream().filter(id -> id.startsWith("12") && id.equals("123")).collect(Collectors.toList());
//对象排序 //正序 List5、list转字符串拼接list = new ArrayList<>(); list.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList()); //反序 list.stream().sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList()); //基本类型集合排序 List ids = new ArrayList<>(); //正序 ids.stream().sorted(); //反序 ids.stream().sorted(Comparator.reverseOrder()); //map按key排序 Map map = new HashMap<>(); List > mapList = new ArrayList<>(map.entrySet()); mapList.sort(Comparator.comparing(Map.Entry::getKey)); //遍历排序map mapList.forEach(entry -> {});
// list通过filter后再转字符串
String collect = ids.stream().filter("123"::equals).collect(Collectors.joining("-"));
// 普通list转字符串
String collect2 = String.join("-", ids);
6、获取对象属性数据转List
List7、统计函数list = new ArrayList<>(); List collect = company.stream().map(User::getAge).collect(Collectors.toList());
Listlist = Arrays.asList(12, 34, 23, 12, 3, 34); IntSummaryStatistics stats = list.stream().mapToInt(x -> x).summaryStatistics(); //最大值 stats.getMax(); //最小值 stats.getMin(); //平均值 stats.getAverage(); //总数 stats.getCount(); //总和 stats.getSum(); s int[] nums = {33, 44, 55, -111, -1}; int min = IntStream.of(nums).min().getAsInt(); System.out.println(min);



