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中间操作
筛选
切片
映射

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

-
查找


max、min、findFirst、findAny返回值都是
Optional<T>类型如果max、min想得到int类型的元素,需要
max().getAsInt()归约



-
收集

| toarray() | 收集成数组 |
|---|---|
Collectors.tomap()方法三个参数,一个表示key,一个表示value,一个表示key冲突怎么办
Stream应用
List 与 Array互转
List 转 Array
List<Integer> --> int[]- 关键操作 mapToInt(Integer::intValue)
List<Integer> integerList = new ArrayList<>();int[] ints = integerList.stream().mapToInt(Integer::intValue).toArray();
- 关键操作 mapToInt(Integer::intValue)
-
Array 转 List
int[] --> List<Integer>- 关键操作 boxed()
int[] ints = new int[100];List<Integer> integerList = Arrays.stream(ints).boxed().collect(Collectors.toList());
- 关键操作 boxed()
String[] --> List<String>String[] strings = new String[100];List<String> stringList = Arrays.stream(strings).collect(Collectors.toList());
对Map的Value进行排序
lambda
Map<Integer, Integer> map = new HashMap<>();List<Map.Entry<Integer, Integer>> mapList = map.entrySet().stream().sorted((c1, c2) -> c2.getValue().compareTo(c1.getValue())).collect(Collectors.toList());
方法引用
List<Map.Entry<Integer, Integer>> mapList = map.entrySet().stream().sorted(Comparator.comparingInt(Map.Entry::getValue)).collect(Collectors.toList());
方法引用
List<Map.Entry<Integer, Integer>> mapList = map.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toList());
如何逆序
List<Map.Entry<Integer, Integer>> mapList = map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue())).collect(Collectors.toList());
求数组极值
int[] nums = new int[100];int max = Arrays.stream(nums).max().getAsInt();
Stream流的基本介绍以及在工作中的常用操作(去重、排序以及数学运算等)
