Stream流式编程

java虽然现在都出到17了,但是java8目前还是用的较多的,是时候把java8新特性用起来了,Stream算是其中比较香的一个了,下面是日常开发中常用的一些api,在这里记录一下。

forEach:遍历流中的数据

该方法接收一个Consumer接口,会将每一个流元素交给函数处理

void forEach(Consumer<? super T> action);

示例:

List<Integer> list = Arrays.asList(1,2,3,4,5,6);
list.stream().forEach(item->{
System.out.println(item);
});
count:统计流中的元素个数

该方法返回一个long值,代表元素的个数

long count();

示例:

List<Integer> list = Arrays.asList(1,2,3,4,5,6);
long count = list.stream().count();
System.out.println(count);
filter:过滤流中的数据,返回符合条件的元素

该方法接收一个Predicate函数式接口,筛选符合条件的数据,返回新的流

Stream filter(Predicate<? super T> predicate);

示例:

Stream.of("abc", "bbb", "ccc", "aaa", "acd")
.filter(s->s.contains("a"))
.forEach(System.out::println);
map: 将流中的每一个元素转换为新的元素,或者转换为其他类型的元素

该方法接收一个Function函数接口,将T类型数据转换为R类型的数据,并返回新的流

Stream map(Function<? super T, ? extends R> mapper);

示例:

Stream.of("abc", "bbb", "ccc", "aaa", "acd")
.map(s -> s+"123")
.forEach(System.out::println);
distinct: 对流中的重复元素去重

该方法不接受任何参数,返回新的流

注意:distinct可对基本数据类型直接去重,而对于自定义类型的去重,要重写该类的equals和hashCode方法

Stream distinct();

示例:


Stream.of("abc", "bbb", "ccc", "aaa", "acd","bbb")
.distinct()
.forEach(System.out::println);
System.out.println("--------------");
Stream.of(
new User(1,"张三"),
new User(2,"李四"),
new User(1,"张三")
).distinct().forEach(System.out::println);
sorted: 对流中的元素排序

该方法接收一个Comparator接口,可以指定排序规则,返回新的流

Stream sorted(Comparator<? super T> comparator);

示例:

//多级排序,优先级低的放前面
        List<Person> sorted2 = list.stream()
                .sorted(((o1, o2) -> o1.getName().compareTo(o2.getName())))
                .sorted(((o1, o2) -> o1.getId() - o2.getId()))
                .collect(Collectors.toList());
        //等价于
//        List<Person> sorted2 = list.stream().sorted(comparing(Person::getId).thenComparing(Person::getName)).collect(Collectors.toList());
        sorted2.forEach(System.out::println);
reduce:对流中的元素做聚合计算

该方法接收一个任意类型的初始值,和一个计算操作的函数式接口,返回值是计算结果

T reduce(T identity, BinaryOperator accumulator);

示例1:

//求和
Integer sum = Stream.of(1, 3, 4, 5, 8)
.reduce(0, (x, y) -> {
System.out.println("x="+x+",y="+y);
return x + y;
});//0表示x的初始值
// x=0,y=1;
// x=1,y=3;
// x=4,y=4;
// x=8,y=5;
// x=13,y=8;
//x=21
System.out.println("reduce聚合结果:"+sum);
//获取最大值
Integer max = Stream.of(1, 3, 4, 5, 8)
.reduce(0, (x, y) -> {
System.out.println("x="+x+",y="+y);
return x > y ? x : y;
});
System.out.println("max:"+max);

示例2:map和reduce的组合

  • map先对原有流数据进行处理,得到可以进行聚合计算的新的流
  • reduce对新流的数据进行聚合计算
//统计所有年龄之和
Integer sumAge = Stream.of(
new Person("张三", 18),
new Person("李四", 19),
new Person("王五", 23),
new Person("赵六", 28)
).map(Person::getAge).reduce(0, (o1, o2) -> o1 + o2);
System.out.println("sum:"+sumAge);
//统计所有年龄中最大值
Integer maxAge = Stream.of(
new Person("张三", 18),
new Person("李四", 19),
new Person("王五", 23),
new Person("赵六", 28)
).map(Person::getAge).reduce(0,(o1,o2)->o1>o2?o1:o2);
System.out.println("max:"+maxAge);
//统计字符数组中a出现的次数
Integer count = Stream.of('a', 'q', 'b', 'a', 'c', 'n', 'a')
.map(x -> x.equals('a') ? 1 : 0)
.reduce(0, (x, y) -> x + y);
System.out.println("count:"+count);
collect: 对处理后的流做结果收集
收集到集合接口

.collect(Collectors.toList()):收集到list集合
.collect(Collectors.toSet()):收集到set集合
.collect(Collectors.toMap(e->e.getId(),e->e)):收集到map集合

示例:

List<String> list = Stream.of("aa", "bb", "cc", "aa")
.collect(Collectors.toList());
System.out.println(list);
Set<String> set = Stream.of("aa", "bb", "cc", "aa")
.collect(Collectors.toSet());
List<Person> list1 = new ArrayList<>();
list.add(new Person(1,"zhangsan"));
list.add(new Person(6,"lisi"));
list.add(new Person(4,"lisi"));
list.add(new Person(3,"lisi"));
list.add(new Person(3,"wangwu"));
list.add(new Person(5,"wangwu"));
Map<Integer, Person> personMap = list.stream().collect(Collectors.toMap(e -> e.getId(), e -> e));
收集到具体集合类

.collect(Collectors.toCollection(() -> new
ArrayList<>())):收集到ArrayList集合 .collect(Collectors.toCollection(() ->
new HashSet<>())):收集到HashSet集合

ArrayList<String> arrayList = Stream.of("aa", "bb", "cc", "aa")
.collect(Collectors.toCollection(() -> new ArrayList<>()));
System.out.println(arrayList);
HashSet<String> hashSet = Stream.of("aa", "bb", "cc", "aa")
.collect(Collectors.toCollection(() -> new HashSet<>()));
System.out.println(hashSet);
收集结果时做聚合运算

Optional a =
list.stream().collect(Collectors.maxBy(Comparator接口):收集结果时求包含最大值的元素,返回值是Optional,不一定有结果
Optional a =
list.stream().collect(Collectors.minBy(Comparator接口):收集结果时求包含最小值的元素,返回值是Optional
Integer sum =
list.stream().collect(Collectors.summarizingInt(ToIntFunction接口)):收集结果时求和,返回值是Integer/Double/Float
float average =
list.stream().collect(Collectors.averagingInt(ToIntFunction接口)).floatValue():收集结果时求平均值,返回值是Float
Long count = list.stream().collect(Collectors.counting()):收集结果时计算个数,返回值是Long

示例:

//求年龄最大的person
Optional<Person> maxAge = Stream.of(
new Person("张三", 18),
new Person("李四", 19),
new Person("王五", 23),
new Person("赵六", 28)
).collect(Collectors.maxBy(((o1, o2) -> o1.getAge() - o2.getAge())));
System.out.println("最大年龄:"+maxAge.get());
//求年龄最小的person
Optional<Person> minAge = Stream.of(
new Person("张三", 18),
new Person("李四", 19),
new Person("王五", 23),
new Person("赵六", 28)
).collect(Collectors.minBy((o1, o2) -> o1.getAge() - o2.getAge()));
System.out.println("最小年龄:"+minAge.get());
//求年龄总和
Integer sumAge = Stream.of(
new Person("张三", 18),
new Person("李四", 19),
new Person("王五", 23),
new Person("赵六", 28)
).collect(Collectors.summingInt(Person::getAge));
System.out.println("年龄总和:"+sumAge);
//求平均年龄
float avgAge = Stream.of(
new Person("张三", 18),
new Person("李四", 19),
new Person("王五", 23),
new Person("赵六", 28)
).collect(Collectors.averagingInt(Person::getAge)).floatValue();
System.out.println("平均年龄:"+avgAge);
//求年龄大于18的记录数
Long count = Stream.of(
new Person("张三", 18),
new Person("李四", 19),
new Person("王五", 23),
new Person("赵六", 28)
).filter(s->s.getAge()>18)
.collect(Collectors.counting());
System.out.println("满足条件的记录数:"+count);
收集结果时做分组计算

Map =
list.stream().collect(Collectors.groupingBy(Function接口)):收集结果时做分组运算,返回值是map

示例:

//根据姓名分组
Map<String, List<Person>> groupByName = Stream.of(
new Person("张三", 18),
new Person("李四", 14),
new Person("张三", 19),
new Person("张三", 23),
new Person("李四", 21)
).collect(Collectors.groupingBy(Person::getName));
groupByName.forEach((k,v)->System.out.println("k:"+k+"\tv:"+v));
//根据年龄分组
final Map<String, List<Person>> groupByAge = Stream.of(
new Person("张三", 18),
new Person("李四", 14),
new Person("张三", 19),
new Person("张三", 23),
new Person("李四", 21)
).collect(Collectors.groupingBy(s -> s.getAge() > 18 ? "成年" : "未成年"));
groupByAge.forEach((k,v)->System.out.println("k:"+k+"\tv:"+v));


//多级分组
Map<String, Map<String, List<Person>>> multiGroupBy = Stream.of(
new Person("张三", 18),
new Person("李四", 14),
new Person("张三", 19),
new Person("张三", 23),
new Person("李四", 21)
).collect(Collectors.groupingBy(Person::getName, Collectors.groupingBy(s -> s.getAge() > 18 ? "成年" : "未成年")));
multiGroupBy.forEach((k,v)->{
System.out.println(k);
v.forEach((k2,v2)->System.out.println("\t"+k2+"\t"+v2));
});
收集结果时做字符串拼接

.collect(Collectors.joining())

示例:


String join1 = Stream.of(
new Person("张三", 18),
new Person("李四", 14),
new Person("张三", 19),
new Person("张三", 23),
new Person("李四", 21)
).map(Person::getName).collect(Collectors.joining());
System.out.println(join1);
String join2 = Stream.of(
new Person("张三", 18),
new Person("李四", 14),
new Person("张三", 19),
new Person("张三", 23),
new Person("李四", 21)
).map(Person::getName).collect(Collectors.joining("_"));
System.out.println(join2);
String join3 = Stream.of(
new Person("张三", 18),
new Person("李四", 14),
new Person("张三", 19),
new Person("张三", 23),
new Person("李四", 21)
).map(Person::getName).collect(Collectors.joining("_", "###", "$$$"));
System.out.println(join3);
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值