Stream基础知识

Stream实例化

通过集合

**new ArrayList<>().stream();** 返回一个顺序流
**map.EntrySet<>().stream();**
**new ArrayList<>().parallelStream();** 返回一个并行流,处理顺序不一定是list中的顺序

通过数组

**Arrays.stream(int[] a)**

  • 通过Stream的of方法

Stream.of(1, 2, 3, 4)

  • 创建无限流

Stream.generate()

Stream中间操作

筛选

image.png

切片

image.png

映射

image.png

  • map相当于一个list中添加一个list,会直接吧list当作一个整的对象,最终list的长度+1
  • flatmap相当于将第二个list拆开,深入到里面把元素取出来,再添加到第一个list中,最终list长度增加第二个list的长度

    排序

    image.png

    Stream终止操作

    匹配

    image.png

  • 返回值为boolean类型

    查找

    image.png
    image.png

  • max、min、findFirst、findAny返回值都是Optional<T>类型

  • 如果max、min想得到int类型的元素,需要max().getAsInt()

    归约

    image.png
    image.png
    image.png

  • identity是初始值

    收集

    image.png

toarray() 收集成数组
  • Collectors.tomap()方法三个参数,一个表示key,一个表示value,一个表示key冲突怎么办

    Stream应用

    List 与 Array互转

    List 转 Array

  • List<Integer> --> int[]

    • 关键操作 mapToInt(Integer::intValue)
      1. List<Integer> integerList = new ArrayList<>();
      2. int[] ints = integerList.stream().mapToInt(Integer::intValue).toArray();
  • List<String> --> String[]

    Array 转 List

  • int[] --> List<Integer>

    • 关键操作 boxed()
      1. int[] ints = new int[100];
      2. List<Integer> integerList = Arrays.stream(ints).boxed().collect(Collectors.toList());
  • String[] --> List<String>

    1. String[] strings = new String[100];
    2. List<String> stringList = Arrays.stream(strings).collect(Collectors.toList());

    对Map的Value进行排序

  • lambda

    1. Map<Integer, Integer> map = new HashMap<>();
    2. List<Map.Entry<Integer, Integer>> mapList = map.entrySet().stream()
    3. .sorted((c1, c2) -> c2.getValue().compareTo(c1.getValue()))
    4. .collect(Collectors.toList());
  • 方法引用

    1. List<Map.Entry<Integer, Integer>> mapList = map.entrySet().stream()
    2. .sorted(Comparator.comparingInt(Map.Entry::getValue))
    3. .collect(Collectors.toList());
  • 方法引用

    1. List<Map.Entry<Integer, Integer>> mapList = map.entrySet().stream()
    2. .sorted(Map.Entry.comparingByValue())
    3. .collect(Collectors.toList());
  • 如何逆序

    1. List<Map.Entry<Integer, Integer>> mapList = map.entrySet().stream()
    2. .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
    3. .collect(Collectors.toList());

    求数组极值

    1. int[] nums = new int[100];
    2. int max = Arrays.stream(nums).max().getAsInt();

    Stream流的基本介绍以及在工作中的常用操作(去重、排序以及数学运算等)