java回顾之stream流、lambda表达式

java回顾之stream流

一、lambda表达式

在开启stream流之前,记录一下lambda表达式,作用是在特定情况下简化代码

格式:

  三部分:

      一对小括号

      一个箭头

      一对大括号(一段代码)

标准格式:

  (一些参数)->{一段代码}

   Collections.sort(list,(Integer o1,Integer o2)->{
            return o2 - o1;
        });

lambda的前提条件

lambda表达式可以代替只有一个抽象方法的接口。

只有一个抽象方法的接口叫"函数式接口".

@FunctionalInterface 验证接口是一个“函数式接口”

省略规则

  • 小括号里面的数据类型可以省略

  • 如果小括号中只有一个参数, 小括号可以省略

  • 如果大括号中只有一行代码,不管有没有返回值,可以同时省略大括号,return关键字和分号

比较器的简化写法:

//Lambda表达式能够自己判断上下文,把多余的内容都去掉
Collections.sort(list,(o1,o2)->o2 - o1);

二、Stream流

Stream流是为了简化常规集合的操作

流相当于"流水线"

2.1、获取流的方式

Collection单列集合
    stream();
    ArrayList<String> list = new ArrayList<>();
    Stream<String> stream = list.stream();

    //Set
    HashSet<String> set = new HashSet<>();
    Stream<String> stream1 = set.stream();

    数组
    Stream.of();
    //数组
    //数组需要写引用类型
    Integer[] arr = {11,22,33,44,55};
    Stream<Integer> arr1 = Stream.of(arr);
Map双列集合[少用]

把键变成单列集合

HashMap<String,Integer> map = new HashMap<>();
//把键变成单列集合
Set<String> set2 = map.keySet();
Stream<String> stream2 = set2.stream();


把值变成单列集合

HashMap<String,Integer> map = new HashMap<>();
//把值变成单列集合
Collection<Integer> coll = map.values();
Stream<Integer> stream3 = coll.stream();

常用方法:
  终结方法:停止了流式操作,不能继续链式编程
    count() 获取元素的个数
    forEach() 遍历每个元素
  非终结方法:返回的依旧是流对象,可以继续链式编程
  filter() 过滤筛选
  limit() 留下前几个
  skip() 删除前几个
  map() 转换流中的数据
  static concat() 合并两个流

三、收集 

流 -----> 数组/集合:
List:
collect(Collectors.toList());
Set:
collect(Collectors.toSet());
数组:
toArray(); 用这个方法变成Object[]

原文地址:https://www.cnblogs.com/gushiye/p/13860865.html