qaq
作用
使用步骤
- 获取Stream流对象
- 使用中间方法处理数据
- 使用终结方法处理数据
获取方式
- 单列集合:
Collection中的默认方法:default Stream<E> stream()
- 双列集合:不可以
- 数组:
Arrays工具类中的静态方法:public static <T> Stream<T> stream(T[] array)
- 一堆零散数据:
Stream接口中的静态方法:public static <T> Stream<T> of(T... values)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| int[] arr1 = {1,2,3,4}; String[] arr2 = {"a","b","c"};
Arrays.stream(arr1).forEach(s -> System.out.println(s));
Arrays.stream(arr2).forEach(s -> System.out.println(s));
Stream.of(1,2,3,4,5).forEach(s -> System.out.println(s));
Stream.of(arr1).forEach(s -> System.out.println(s));
|
中间方法
Stream<T> filter(Predicate<? super T>predicate):过滤
Stream<T> limit(long maxSize):获取前几个元素
Stream<T> skip(long n):跳过前几个元素
Stream<T> distinct():元素去重,依赖(hashCode和equals方法),底层用的HashSet
static <T> Stream<T> concat(Stream a, Stream b):合并a和b两个流为一个流
Stream<R> map(Function<T, R> mapper):转换流中的数据类型
注意
:会返回新的Stream流,原来的Stream流只能使用一次
1 2 3 4 5
| ArrayList<String> list = new ArrayList<>(); Collections.addAll(list, "a", "b", "c");
list.stream().filter(s -> s.startWith("a")). forEach(s -> System.out.println(s));
|
终结方法
void forEach(Consumer action):遍历
long count():统计
toArray():把流中数据收集到数组中
collect(Collector collector):把流中数据收到集合中
1
| String[] arr = list.stream().toArray(value -> new String[value]);
|
1 2 3 4
| List<String> newList = list.stream().filter(s -> "男".equals(s.split("-")[1])).collect(Collectors.toList());
Set<String> newSet = list.stream().filter(s -> "男".equals(s.split("-")[1])).collect(Collectors.toSet());
|
示例代码
1 2 3 4 5 6
| ArrayList<Integer> list = new ArrayList<>(); Collections.addAll(list, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); List<Integer> newList = list.stream() .filter(s -> s%2 == 0) .collect(Collectors.toList()); System.out.println(newList);
|
1 2 3 4 5 6 7 8 9
| ArrayList<String> list = new ArrayList<>(); list.add("zhangsan,23"); list.add("lisi,24"); list.add("wangwu,25");
Map<String, Integer> mp = list.stream() .filter(s -> Integer.parseInt(s.split(",")[1]) >= 24) .collect(Collectors.toMap(s -> s.split(",")[0], s -> Integer.parseInt(s.split(",")[1]))); System.out.println(mp);
|