> 文档中心 > Java8新特性Lambda + Stream表达式

Java8新特性Lambda + Stream表达式


一、简介

1、Lambda标准格式

  • 三部分

  • 一些参数

  • 一个箭头

  • 一段代码

  • 格式

    • (参数列表) -> (重写方法的代码)
    • () :—> 没有参数就空着,有参数就写参数,多个参数都好分割
    • -> :—> 传递的意思
    • {} :—>重写抽象方法的方法体

2、Lambda表达式

  • Lambda表达式是可推导,可省略
  • 可省略的内容
    • (参数列表): 括号参数列表的数据类型可以省略不写
    • (参数列表): 括号的参数如果只有一个,那么类型和()都可以省略
    • (一些代码): 如果{}中的代码只有一行,无论是否有返回值,都可以省略({},return,分号)
    • 要省略{},return,分号必须一起省略

3、Lambda表达式使用前提

  • 使用Lambda必须要有接口,且要求接口中有且仅有一个抽象方法

    比如通过new Tread创建线程时使用。

二、使用

1、遍历(forEach)

//Map对象Map<String,String> map= new HashMap<>(); map.forEach((k,v)->{     // 打印键     System.out.println(k);     // 打印值     System.out.println(v); });//list对象 List<Stu> list = new ArrayList(); list.forEach((l)->{     System.out.println(l.getId());     System.out.println(l.getName()); });//Set对象 Set<Stu> set = new HashSet<>(); set.forEach((s)->{     System.out.println(s.getId());     System.out.println(s.getName()); });

2、遍历操作(map)

List<String> ids = new ArrayList<>();List<String> collect = ids.stream().map(a -> a + "123").collect(Collectors.toList());

3、条件过滤

//对象数据List<User> list = new ArrayList<>();List<User> collect = list.stream().filter(user -> !"张三".equals(user.getName())).collect(Collectors.toList());//单一数组List<String> ids = new ArrayList<>();List<String> collect = ids.stream().filter(id -> id.startsWith("12") && id.equals("123")).collect(Collectors.toList());

4、排序

//对象排序//正序List<User> 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<Integer> ids = new ArrayList<>();//正序ids.stream().sorted();//反序ids.stream().sorted(Comparator.reverseOrder());//map按key排序Map<Integer, Object> map = new HashMap<>();List<Map.Entry<Integer, Object>> mapList = new ArrayList<>(map.entrySet());mapList.sort(Comparator.comparing(Map.Entry::getKey));//遍历排序mapmapList.forEach(entry -> {});

5、list转字符串拼接

// list通过filter后再转字符串String collect = ids.stream().filter("123"::equals).collect(Collectors.joining("-"));// 普通list转字符串String collect2 = String.join("-", ids);

6、获取对象属性数据转List

List<User> list = new ArrayList<>();List<Integer> collect = company.stream().map(User::getAge).collect(Collectors.toList());

7、统计函数

List<Integer> list = 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();sint[] nums = {33, 44, 55, -111, -1}; int min = IntStream.of(nums).min().getAsInt(); System.out.println(min);