Stream流操作
准备工作
准备 Gender 枚举类以及 Customer 类
enum Gender {MALE("男性"), FEMALE("女性");private String value;Gender() {}Gender(String value) {this.value = value;}@Overridepublic String toString() {return "Gender{" +"value='" + value + '\'' +'}';}
}
class Customer {private String name;private Gender gender;public Customer() {}public Customer(String name, Gender gender) {this.name = name;this.gender = gender;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Gender getGender() {return gender;}public void setGender(Gender gender) {this.gender = gender;}@Overridepublic String toString() {return "Customer{" +"name='" + name + '\'' +", gender=" + gender +'}';}
}
Stream 介绍
java.util.Stream
表示能应用在一组元素上一次执行的操作序列。- Stream操作分为中间操作或者最终操作两种,最终操作返回一特定类型的计算结果,而中间操作返回Stream本身,可以连续完成多个操作。
创建 Stream 流
创建数据流的方式一
// 创建数据流方法一 使用集合.stream()
List<String> list = Arrays.asList("c", "c++", "c#", "java", "python", "go", "php", "html", "visual basic", "visual basic", "visual basic", "basic", "basic", "b");
list.stream();
创建数据流的方式二
// 创建数据流方法二 使用Stream.of()
Stream<String> stream2 = Stream.of("C", "C++", "c#", "Java", "python", "Go", "php", "html", "visual basic", "visual basic", "visual basic", "basic", "basic", "B");
常用方法
1. forEach 遍历方法
重写 Consumer
函数式接口中的 apply() 方法
List<String> list = Arrays.asList("c", "c++", "c#", "java", "python", "go", "php", "html", "visual basic", "visual basic", "visual basic", "basic", "basic", "b");
Stream<String> stream1 = list.stream();
stream1.forEach(System.out::println);
2. filter 过滤方法
按照条件过滤掉出我们需要的数据
List<String> list = Arrays.asList("c", "c++", "c#", "java", "python", "go", "php", "html", "visual basic", "visual basic", "visual basic", "basic", "basic", "b");
Stream<String> stream1 = list.stream();
stream1.filter((lang) -> {return lang.length() > 3;
})
.distinct() //去重
.forEach(System.out::println);
3. sorted 排序方法
重写Comparator
函数式接口中的compare()
方法
Stream<String> stream2 = Stream.of("C", "C++", "c#", "Java", "python", "Go", "php", "html", "visual basic", "visual basic", "visual basic", "basic", "basic", "B");
// 获得包含大写字母的并且排序
stream2.filter((lang) -> {for (int i = 0; i < lang.length(); i++) {if (lang.charAt(i) >= 'A' && lang.charAt(i) <= 'Z') {return true;}}return false;
}).sorted((o1, o2) -> {int compare = o1.compareTo(o2);if (compare == 0) {return o1.length() - o2.length();} else {return compare;}
}).forEach((lang) -> {System.out.println(lang);
});
4. map 映射方法
映射 对流中的数据进行处理(加减乘除等等操作)
// 将集合中的数据每个都 +1
List<Integer> numList = Arrays.asList(90, 100, 10, 20, 30, 50, 60, 70, 80);
numList.stream().map((num) -> {return num + 1;
}).forEach(System.out::println);
5. match 匹配方法
- 返回值是一个
boolean
类型 - 重写函数式接口
Predicate
接口中的test()
方法
allMatch()
全部匹配,只有集合中的数据全部匹配我们的条件才会返回true
List<String> strings = Arrays.asList("abc", "defs", "gkh", "abc");
boolean bool = strings.stream().allMatch((s) -> {return s.length() == 3;
});
System.out.println(bool);
运行结果为 false
因为有一个数据的长度是 4
anyMatch()
部分匹配,只要集合中的数据有一个匹配我们的条件就返回true
List<String> strings = Arrays.asList("abc", "defs", "gkh", "abc");boolean bool = strings.stream().anyMatch((s) -> {return s.length() == 3;
});
System.out.println(bool);
6. count 计数方法
用来统计个数类似于 sql
中的聚合函数 count
/*** 计数 count()* 统计所有女生的数量*/
List<Customer> customerList = Arrays.asList(new Customer("白骨精", Gender.FEMALE),new Customer("女儿国国王", Gender.FEMALE),new Customer("擎天柱", Gender.MALE),new Customer("蛇精", Gender.FEMALE),new Customer("金刚葫芦娃", Gender.MALE));
// 先过滤在统计
long count = customerList.stream().filter((customer) -> {return customer.getGender().equals(Gender.MALE);
}).count();
System.out.println(count);
7. collect 收集方法
toMap()
收集每个元素的长度(元素为key
,长度为value
)转换成一个map
Map<String, Integer> map = Stream.of("C", "C++", "c#", "Java", "python", "Go", "php", "html", "visual basic", "visual basic", "visual basic", "basic", "basic", "B")
.distinct() //去重 因为这里不能做到覆盖操作 键重复会报错
.collect(Collectors.toMap((s) -> {return s;
}, (s) -> {return s.length();
}));
System.out.println(map);
mapping()
映射方法
将 Stirng
类型的元素转换成 int
类型并且都乘以 100
List<Integer> integerList = Stream.of("10", "20", "60", "50", "70", "90")
.collect(Collectors.mapping((s) -> {return Integer.parseInt(s) * 100;
}, Collectors.toList()));
integerList.forEach(System.out::println);
groupingBy()
分组操作,可按条件分为若干组
- 按照元素的长度分组
Stream.of("C", "C++", "c#", "Java", "python", "Go", "php", "html", "visual basic", "visual basic", "visual basic", "basic", "basic", "B")
.collect(Collectors.groupingBy((s) -> {return s.length(); // 按照元素的长度分组
}))
.forEach((k, v) -> {System.out.println(k + ":" + v);
});
- 按照元素的首字母分组
Stream.of("C", "C++", "c#", "Java", "python", "Go", "php", "html", "visual basic", "visual basic", "visual basic", "basic", "basic", "B")
.collect(Collectors.groupingBy((s) -> {return s.charAt(0);
}))
.forEach((k, v) -> {System.out.println(k + ":" + v);
});
partitioningBy()
分区操作 将元素按条件分为两区,一区是符合条件的,一 区 是不符合条件的
Stream.of("C", "C++", "c#", "Java", "python", "Go", "php", "html", "visual basic", "visual basic", "visual basic", "basic", "basic", "B")
.collect(Collectors.partitioningBy((s) -> {return s.length() >= 3;
})).forEach((k, v) -> {System.out.println(k + ":" + v);
});
8. 统计操作
常见的有 mapToInt()
、mapToDouble()
、mapToLong()
这里使用的是mapToInt()
统计操作可以获得元素的最大值、最小值、平均值、累加值、以及元素个数
List<Integer> numList1 = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
// stream ==> IntStream
IntStream intStream = numList1.stream().mapToInt((n) -> {return n;
});
// 获得统计结果
IntSummaryStatistics statistics = intStream.summaryStatistics();
System.out.println("最大值" + statistics.getMax());
System.out.println("最小值" + statistics.getMin());
System.out.println("平均值" + statistics.getAverage());
System.out.println("累加值" + statistics.getSum());
System.out.println("元素个数" + statistics.getCount());