java的Stream流
一、遍历与统计
// forEach遍历
ArrayList<String> list1 = new ArrayList<>();
Collections.addAll(list1, "张无忌", "张三A", "张三B", "张三C",
"周五", "李四", "赵本三");
list1.stream().forEach(System.out::println);
// count 统计
Long num = list1.stream().count();
System.out.println(num);
// toArray 收集变成数组
String[] str = list1.stream().toArray(value -> new String[value]);
System.out.println(Arrays.toString(str));
二、Stream的常见方法
1、filter 过滤,limit获取前几个元素,skip跳过前几个元素
ArrayList<String> list1 = new ArrayList<>();
Collections.addAll(list1, "张无忌", "张三A", "张三B", "张三C",
"周五", "李四", "赵本三");
// 需求:张开头,最大数量为3,跳过第一个,打印
list1.stream()
.filter(s -> s.startsWith("张")) //张开头
.limit(3) // 最大数量为3
.skip(1) //跳过第一个
.forEach(System.out::println);
/*
结果:
张三A
张三B
*/
2、map 转化流转的两种数据类型
ArrayList<String> list1 = new ArrayList<>();
Collections.addAll(list1, "张无忌-1", "张三A-2",
"张三B-3", "张三C-4",
"周五-5", "李四-6", "赵本三-7");
System.out.println(list1);
// 字符串转为整型
list1.stream()
.map(s -> Integer.parseInt(s.split("-")[1]))
.forEach(s-> System.out.print(s + " "));
3、distinct去重
ArrayList<String> list1 = new ArrayList<>();
Collections.addAll(list1, "张无忌", "张无忌", "张无忌", "张三C",
"周五", "李四", "赵本三");
list1.stream().distinct().forEach(System.out::println);
4、concat 合并两个流
ArrayList<String> list1 = new ArrayList<>();
Collections.addAll(list1, "a","b","c");
ArrayList<String> list2 = new ArrayList<>();
Collections.addAll(list2, "d","e","f");
Stream.concat(list1.stream(),list2.stream()).forEach(System.out::println);
三、Stream的收集
使用Java的Stream API对一个包含字母-性别-编号
格式字符串的ArrayList
进行处理:首先通过filter
筛选出性别为“男”的元素,分别收集到List
和Set
中;然后通过toMap
将每个字符串的字母作为键、编号作为值,收集到Map
中,最终实现了对数据的分类和转换。
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "A-男-01", "B-男-02", "C-男-03",
"D-男-04", "E-女-05",
"F-女-06", "G-男-07");
// 需求一:用list把男生收集起来
List<String> list1 = list.stream()
.filter(s -> "男".equals(s.split("-")[1]))
.collect(Collectors.toList());
System.out.println(list1);
// 需求二:用set把男生收集起来
Set<String> list2 = list.stream()
.filter(s -> "男".equals(s.split("-")[1]))
.collect(Collectors.toSet());
System.out.println(list2);
// 需求三:用map收集所有信息,字母对应编号
// ps:map收集不能有两个键相同
Map<String, Integer> map = list.stream()
.collect(
Collectors.toMap(
s -> s.split("-")[0],
s -> Integer.parseInt(s.split("-")[2])
)
);
System.out.println(map);