JDK8 之 Stream流
2,036 字8 min read
Stream常用方法
Stream流模型的操作很丰富,这里介绍一些常用的API。这些方法可以被分成两种:
| 方法名 | 方法作用 | 返回值类型 | 方法种类 |
|---|---|---|---|
| count | 统计个数 | long | 终结 |
| forEach | 逐一处理 | void | 终结 |
| filter | 过滤 | Stream | 函数拼接 |
| limit | 取用前几个 | Stream | 函数拼接 |
| skip | 跳过前几个 | Stream | 函数拼接 |
| map | 映射 | Stream | 函数拼接 |
| concat | 组合 | Stream | 函数拼接 |
forEach用来遍历流中的数据
public static void main(String[] args) {
Stream.of("a1", "a2", "a3").forEach(System.out::println);;
}
count方法用来统计其中的元素个数
public static void main(String[] args) {
long count = Stream.of("a1", "a2", "a3").count();
System.out.println(count);
}
通过filter方法将一个流转换成另一个子集流
该接口接收一个Predicate函数式接口参数作为筛选条件
public static void main(String[] args) {
Stream.of("a1", "a2", "a3","bb","cc","aa","dd")
.filter((s)->s.contains("a"))
.forEach(System.out::println);
}
limit方法可以对流进行截取处理,支取前n个数据
public static void main(String[] args) {
Stream.of("a1", "a2", "a3","bb","cc","aa","dd")
.limit(3)
.forEach(System.out::println);
}
skip:跳过前面几个元素,获取一个截取之后的新流
public static void main(String[] args) {
Stream.of("a1", "a2", "a3","bb","cc","aa","dd")
.skip(3)
.forEach(System.out::println);
}
map方法将流中的元素映射到另一个流中
public static void main(String[] args) {
Stream.of("1", "2", "3","4","5","6","7")
//.map(msg->Integer.parseInt(msg))
.map(Integer::parseInt)
.forEach(System.out::println);
}
sorted在使用的时候可以根据自然规则排序,也可以通过比较强来指定对应的排序规则
public static void main(String[] args) {
Stream.of("1", "3", "2","4","0","9","7")
//.map(msg->Integer.parseInt(msg))
.map(Integer::parseInt)
//.sorted() // 根据数据的自然顺序排序
.sorted((o1,o2)->o2-o1) // 根据比较强指定排序规则
.forEach(System.out::println);
}
如果要去掉重复数据,可以使用distinct方法:
public static void main(String[] args) {
Stream.of("1", "3", "3","4","0","1","7")
//.map(msg->Integer.parseInt(msg))
.map(Integer::parseInt)
//.sorted() // 根据数据的自然顺序排序
.sorted((o1,o2)->o2-o1) // 根据比较强指定排序规则
.distinct() // 去掉重复的记录
.forEach(System.out::println);
System.out.println("--------");
Stream.of(
new Person("张三",18)
,new Person("李四",22)
,new Person("张三",18)
).distinct()
.forEach(System.out::println);
}
match:判断数据是否匹配指定的条件
public static void main(String[] args) {
boolean b = Stream.of("1", "3", "3", "4", "5", "1", "7")
.map(Integer::parseInt)
//.allMatch(s -> s > 0)
//.anyMatch(s -> s >4)
.noneMatch(s -> s > 4);
System.out.println(b);
}
find:们需要找到某些数据
public static void main(String[] args) {
Optional<String> first = Stream.of("1", "3", "3", "4", "5", "1",
"7").findFirst();
System.out.println(first.get());
Optional<String> any = Stream.of("1", "3", "3", "4", "5", "1",
"7").findAny();
System.out.println(any.get());
}
max和min
public static void main(String[] args) {
Optional<Integer> max = Stream.of("1", "3", "3", "4", "5", "1", "7")
.map(Integer::parseInt)
.max((o1,o2)->o1-o2);
System.out.println(max.get());
Optional<Integer> min = Stream.of("1", "3", "3", "4", "5", "1", "7")
.map(Integer::parseInt)
.min((o1,o2)->o1-o2);
System.out.println(min.get());
}
reduce方法
如果需要将所有数据归纳得到一个数据,可以使用reduce方法
public static void main(String[] args) {
Integer sum = Stream.of(4, 5, 3, 9)
// identity默认值
// 第一次的时候会将默认值赋值给x
// 之后每次会将 上一次的操作结果赋值给x y就是每次从数据中获取的元素
.reduce(0, (x, y) -> {
System.out.println("x="+x+",y="+y);
return x + y;});
System.out.println(sum);
// 获取 最大值
Integer max = Stream.of(4, 5, 3, 9)
.reduce(0, (x, y) -> {
return x > y ? x : y;});
System.out.println(max);
}
map和reduce的组合
public static void main(String[] args) {
// 1.求出所有年龄的总和
Integer sumAge = Stream.of(
new Person("张三", 18)
, new Person("李四", 22)
, new Person("张三", 13)
, new Person("王五", 15)
, new Person("张三", 19)
).map(Person::getAge) // 实现数据类型的转换
.reduce(0, Integer::sum);
System.out.println(sumAge);
// 2.求出所有年龄中的最大值
Integer maxAge = Stream.of(
new Person("张三", 18)
, new Person("李四", 22)
, new Person("张三", 13)
, new Person("王五", 15)
, new Person("张三", 19)).map(Person::getAge) // 实现数据类型的转换,符合reduce对数据的要求
.reduce(0, Math::max); // reduce实现数据的处理
System.out.println(maxAge);
// 3.统计 字符 a 出现的次数
Integer count = Stream.of("a", "b", "c", "d", "a", "c", "a")
.map(ch -> "a".equals(ch) ? 1 : 0)
.reduce(0, Integer::sum);
System.out.println(count);
}
mapToInt
如果需要将Stream中的Integer类型转换成int类型,可以使用mapToInt方法来实现
public static void main(String[] args) {
// Integer占用的内存比int多很多,在Stream流操作中会自动装修和拆箱操作
Integer arr[] = {1,2,3,5,6,8};
Stream.of(arr)
.filter(i->i>0)
.forEach(System.out::println);
System.out.println("---------");
// 为了提高程序代码的效率,我们可以先将流中Integer数据转换为int数据,然后再操作
IntStream intStream = Stream.of(arr)
.mapToInt(Integer::intValue);
intStream.filter(i->i>3)
.forEach(System.out::println);
}
concat
如果有两个流,希望合并成为一个流,那么可以使用Stream接口的静态方法concat
public static void main(String[] args) {
Stream<String> stream1 = Stream.of("a","b","c");
Stream<String> stream2 = Stream.of("x", "y", "z");
// 通过concat方法将两个流合并为一个新的流
Stream.concat(stream1,stream2).forEach(System.out::println);
}
Stream结果收集
结果收集到集合中
@Test
public void test01(){
// Stream<String> stream = Stream.of("aa", "bb", "cc");
List<String> list = Stream.of("aa", "bb", "cc","aa")
.collect(Collectors.toList());
System.out.println(list);
// 收集到 Set集合中
Set<String> set = Stream.of("aa", "bb", "cc", "aa")
.collect(Collectors.toSet());
System.out.println(set);
// 如果需要获取的类型为具体的实现,比如:ArrayList HashSet
ArrayList<String> arrayList = Stream.of("aa", "bb", "cc", "aa")
//.collect(Collectors.toCollection(() -> new ArrayList<>()));
.collect(Collectors.toCollection(ArrayList::new));
System.out.println(arrayList);
HashSet<String> hashSet = Stream.of("aa", "bb", "cc", "aa")
.collect(Collectors.toCollection(HashSet::new));
System.out.println(hashSet);
}
结果收集到数组中
@Test
public void test02(){
Object[] objects = Stream.of("aa", "bb", "cc", "aa")
.toArray(); // 返回的数组中的元素是 Object类型
System.out.println(Arrays.toString(objects));
// 如果我们需要指定返回的数组中的元素类型
String[] strings = Stream.of("aa", "bb", "cc", "aa")
.toArray(String[]::new);
System.out.println(Arrays.toString(strings));
}
对流中的数据做聚合计算
public void test03(){
// 获取年龄的最大值
Optional<Person> maxAge = Stream.of(
new Person("张三", 18)
, new Person("李四", 22)
, new Person("张三", 13)
, new Person("王五", 15)
, new Person("张三", 19)
).collect(Collectors.maxBy((p1, p2) -> p1.getAge() - p2.getAge()));
System.out.println("最大年龄:" + maxAge.get());
// 获取年龄的最小值
Optional<Person> minAge = Stream.of(
new Person("张三", 18)
, new Person("李四", 22)
, new Person("张三", 13)
, new Person("王五", 15)
, new Person("张三", 19)
).collect(Collectors.minBy((p1, p2) -> p1.getAge() - p2.getAge()));
System.out.println("最新年龄:" + minAge.get());
// 求所有人的年龄之和
Integer sumAge = Stream.of(
new Person("张三", 18)
, new Person("李四", 22)
, new Person("张三", 13)
, new Person("王五", 15)
, new Person("张三", 19)
)
//.collect(Collectors.summingInt(s -> s.getAge()))
.collect(Collectors.summingInt(Person::getAge))
;
System.out.println("年龄总和:" + sumAge);
// 年龄的平均值
Double avgAge = Stream.of(
new Person("张三", 18)
, new Person("李四", 22)
, new Person("张三", 13)
, new Person("王五", 15)
, new Person("张三", 19)
).collect(Collectors.averagingInt(Person::getAge));
System.out.println("年龄的平均值:" + avgAge);
// 统计数量
Long count = Stream.of(
new Person("张三", 18)
, new Person("李四", 22)
, new Person("张三", 13)
, new Person("王五", 15)
, new Person("张三", 19)
).filter(p->p.getAge() > 18)
.collect(Collectors.counting());
System.out.println("满足条件的记录数:" + count);
}
对流中数据做分组操作
/**
* 分组计算--多级分组
*/
@Test
public void test05(){
// 先根据name分组,然后根据age(成年和未成年)分组
Map<String,Map<Object,List<Person>>> map = Stream.of(
new Person("张三", 18, 175)
, new Person("李四", 22, 177)
, new Person("张三", 14, 165)
, new Person("李四", 15, 166)
, new Person("张三", 19, 182)
).collect(Collectors.groupingBy(
Person::getName
,Collectors.groupingBy(p->p.getAge()>=18?"成年":"未成年"
)
));
map.forEach((k,v)->{
System.out.println(k);
v.forEach((k1,v1)->{
System.out.println("\t"+k1 + "=" + v1);
});});}
对流中的数据做拼接
**
* 对流中的数据做拼接操作
*/
@Test
public void test07(){
String s1 = Stream.of(
new Person("张三", 18, 175)
, new Person("李四", 22, 177)
, new Person("张三", 14, 165)
, new Person("李四", 15, 166)
, new Person("张三", 19, 182)
).map(Person::getName)
.collect(Collectors.joining());
// 张三李四张三李四张三
System.out.println(s1);
String s2 = Stream.of(
new Person("张三", 18, 175)
, new Person("李四", 22, 177)
, new Person("张三", 14, 165)
, new Person("李四", 15, 166)
, new Person("张三", 19, 182)
).map(Person::getName)
.collect(Collectors.joining("_"));
// 张三_李四_张三_李四_张三
System.out.println(s2);
String s3 = Stream.of(
new Person("张三", 18, 175)
, new Person("李四", 22, 177)
, new Person("张三", 14, 165)
, new Person("李四", 15, 166)
, new Person("张三", 19, 182)
).map(Person::getName)
.collect(Collectors.joining("_", "###", "$$$"));
// ###张三_李四_张三_李四_张三$$$
System.out.println(s3);
}讨论
评论区尚未启用。