java8 stream().map().collect()用法

原创:https://blog.csdn.net/az44yao

 

有一个集合:

List<User> users = getList(); //从数据库查询的用户集合

现在想获取User的身份证号码;在后续的逻辑处理中要用;

常用的方法我们大家都知道,用for循环,

List<String> idcards=new ArrayList<String>();//定义一个集合来装身份证号码

for(int i=0;i<users.size();i++){

  idcards.add(users.get(i).getIdcard());

}

这种方法要写好几行代码,有没有简单点的,有,java8 API能一行搞定:

List<String> idcards= users.stream().map(User::getIdcard).collect(Collectors.toList())

解释下一这行代码:

users:一个实体类的集合,类型为List<User>
User:实体类
getIdcard:实体类中的get方法,为获取User的idcard
 

 

stream()优点

无存储。stream不是一种数据结构,它只是某种数据源的一个视图,数据源可以是一个数组,Java容器或I/O channel等。
为函数式编程而生。对stream的任何修改都不会修改背后的数据源,比如对stream执行过滤操作并不会删除被过滤的元素,而是会产生一个不包含被过滤元素的新stream。
惰式执行。stream上的操作并不会立即执行,只有等到用户真正需要结果的时候才会执行。
可消费性。stream只能被“消费”一次,一旦遍历过就会失效,就像容器的迭代器那样,想要再次遍历必须重新生成。
stream().map()方法的使用示例:

 

再看几个例子:数组字母小写变大写
List<String> list= Arrays.asList("a", "b", "c", "d");

List<String> collect =list.stream().map(String::toUpperCase).collect(Collectors.toList());
System.out.println(collect); //[A, B, C, D]

数组所有元素,按某种规律计算:
List<Integer> num = Arrays.asList(1,2,3,4,5);
List<Integer> collect1 = num.stream().map(n -> n * 2).collect(Collectors.toList());
System.out.println(collect1); //[2, 4, 6, 8, 10]

 

 

Collectors.toList()的理解

https://www.cnblogs.com/zhvip/p/12839019.html

Collectors.toList()用来结束Stream流。

复制代码

    public static void main(String[] args) {

        List<String> list = Arrays.asList("hello","world","stream");
        list.stream().map(item->item+item).collect(Collectors.toList()).forEach(System.out::println);
        list.stream().map(item->item+item).collect(
                ArrayList::new,
                (list1,value )-> list1.add(value),
                (list1 ,list2)-> list1.addAll(list2)
                ).forEach(System.out::println);

    }

复制代码

    <R> R collect(Supplier<R> supplier,
                  BiConsumer<R, ? super T> accumulator,
                  BiConsumer<R, R> combiner);

从文档上我们可以知道,collect()方法接收三个函数式接口

 

  • supplier表示要返回的类型,Supplier<R> supplier不接收参数,返回一个类型,什么类型,这里是ArrayList类型,所以是ArrayList::new
  • BiConsumer<R, ? super T> accumulator接收两个参数,一个是返回结果(ArrayList),一个是stream中的元素,会遍历每一个元素,这里要做的是把遍历的每一个元素添加到要返回的ArrayList中,所以第二个参数(list1,value )-> list1.add(value),
  • BiConsumer<R, R> combiner接收两个参数,一个是返回结果,一个是遍历结束后得到的结果,这里要把遍历结束后得到的list添加到要返回的list中去,所以第三个参数是,(list1 ,list2)-> list1.addAll(list2)
 
    public static <T>
    Collector<T, ?, List<T>> toList() {
        return new CollectorImpl<>((Supplier<List<T>>) ArrayList::new, List::add,
                                   (left, right) -> { left.addAll(right); return left; },
                                   CH_ID);
    }

我们可以看到,Collectors.toList()默认也是这么实现的,所以他们两种写法是等价的。

 

kotlin 代码 直接用

 whellpicker1.setData(mPresenter.dataList.map({ it.childname }))






posted @ 2021-01-18 15:57  风骚羊肉串  阅读(3243)  评论(0编辑  收藏  举报