java8之stream常见方法

一、map

通过名字知道这是个映射关系。

1.1、方法定义

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

1.2、英文原意

Returns a stream consisting of the results of applying the given function to the elements of this stream.
把这个流中的元素都经过function的调用,然后把function调用的所有结果再组成一个流。

1.3 代码演示

 Stream<String> stream = Stream.of("1","2","3");

 Stream<Integer> mapResult =  stream.map(str->Integer.parseInt(str));

二、flatMap

扁平化映射,这个从字面理解有点难

2.1、方法定义

<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
  1. 先理解function的转换结果:? extends Stream<? extends R>,首先 ?是一个流,也就是说function转换结果必须是个流,然后这个流的上边界是 Stream<? extends R>。
  2. 在理解flatMap返回值Stream <R> : 假如 调用者的流有10个元素,经过function后会变成10个流,但是结果却不是一个具有长度为10的流数组,而是成为了一个大的流。 这也就是flatmap叫做合并流的原因

2.2、英文原意

Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element
把这个流中的元素都经过function的调用,然后把经过function调用产生的流组成一个流返回

2.3 代码演示

 Stream<String> stream = Stream.of("hello","world");

 Stream<String> flatMapResult = stream.flatMap(str-> Arrays.stream(str.split("")));

 flatResult.forEach(System.out::print);

 Stream<String[]>  mapResult =  stream.map(str->str.split(""));

flatMapResult: h e l l o w o r l d

三、分组

3.3 代码演示

 public void testGroup(){
        List<User> list = new ArrayList();
        list.add(new User(10,"a"));
        list.add(new User(11,"b"));
        list.add(new User(12,"c"));
        list.add(new User(10,"d"));

        Map<Integer,List<User>> map =  list.stream().collect(Collectors.groupingBy(User::getAge));
        map.forEach((age,lists)->{
            System.out.println("age:"+age+",group size:"+lists.size());
        });

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值