Java 8 Streams部分API简介

     写在前面,下面的链式调用曾经让我惊艳过。有时,我会想,一行代码如此之长是否真的合适,出了错也许会比较难找,(比如某个set返回不是MsgInfo对象而是null的话,定位都会是这一行),然而,这不妨碍心中莫名其妙的自豪感,身为码农,最重要的不是对自己流利代码和自身高尚品质的绝对自信么?笑:-D

MsgInfo msgInfo = new MsgInfo();
        msgInfo.setOwnerId("100011002")
                .setRelatedId("1000110003")
                .setBody("hello 链式调用")
                .setType(MsgInfo.Type.TEXT)
                .setDirect(MsgInfo.Direct.SEND)
                .setStatus(MsgInfo.Status.SENDING)
                .setTime(System.currentTimeMillis());
    

    前言说完,这一次的Stream也是可以同样做到长链式调用从而完成原先需要许多行代码才能实现的事。

    参考内容写在前面,因为这篇文章比我的全面许多,我只是列举一个实践中常用,此外,文章中还有有趣的Optional的用法简介,也是很棒的学习内容,在findFirst这个API中。

    这就是链接啦:我是链接

    

    总算开始说正文了。。。

    先记住这么一条重要提示:Variable used in lambda expression should be final or effectively final.这意味可以在Stream中使用外部变量,但是却不能进行赋值操作。大概如下的这个样子:(Newsarticle是我自己建的对象)

articleList=newsArticleMapper.getArticleList(typeid, offset, size);
                    NewsArticle a=new NewsArticle();
                    int i=0;
                    articleList.stream().forEach(temp->{
                        temp.setNewsTags(Arrays.asList(temp.getNewsTag().split(" ")));
                        redisApi.addObjToList(articleListKey,temp);
                        NewsArticle b=new NewsArticle();
                        a.setNewsId(111);//ok
                        a.getNewsTag();//ok
                        b=a;//ok
                        a=new NewsArticle();//error
                        a=b;//error
                        i++;//error
                    });

     似乎跑偏了,接下去是常用的几个API: filter、map、forEach、sorted、findFirst、reduce、limit/skip、min/max/distinct、allMatch/anyMatch/noneMatch,有几个会举例说明(毕竟自己写了啊~~)


先建个list吧,以下例子都是以这个list为前提的:

List<Integer> list=new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);
        list.add(7);

filter:筛选出符合某个条件的元素

list.stream().filter(p->p>2).forEach(temp->System.out.println(temp));

map:把input Stream的每一个元素,映射成output Stream的另外一个元素。超级好用!!!!!

List<String> list2=list.stream().map(p->p+"aaaaaaa").collect(Collectors.toList());
        list2.stream().forEach(temp->System.out.println(temp));

forEach:遍历每一个元素,对这个元素执行某项操作(可以是一段代码~~~~)

list.stream().forEach(p->{
            p=p+100;
            System.out.println(p);
        });


sorted:如其名一般,用以实现排序,比如下面的倒序实现。(实质是实现两个元素的可比)

list.stream().sorted((p1,p2)-> {
           return p2 - p1;
        }).forEach(temp->System.out.println(temp));

下面几个偷懒不写啦~~~~

findFirst:返回Stream的第一个元素,或者空。

reduce:这个方法的主要作用是把 Stream 元素组合起来。它提供一个起始值(种子),然后依照运算规则(BinaryOperator),和前面 Stream 的第一个、第二个、第 n 个元素组合。

limit/skip:limit 返回 Stream 的前面 n 个元素;skip 则是扔掉前 n 个元素。

min/max/distinct:min/max取最小/最大值,使用 distinct 来找出不重复的单词。

allMatch/anyMatch/noneMatch:allMatch:Stream 中全部元素符合传入的 predicate,返回 true;anyMatch:Stream 中只要有一个元素符合传入的 predicate,返回 true;noneMatch:Stream 中没有一个元素符合传入的 predicate,返回 true。


值得注意的是,这些操作都不会改变List中元素本身(基本类型保持值不变,对象可以改变属性的值),需要.collect(Collectors.toList())将其组织成另一个对象。

举例来说这个样子:

List<Integer> list2=list.stream().filter(p->p>2).collect(Collectors.toList());
        list.stream().forEach(temp->System.out.println(temp));//1、2、3、4、5、6、7
        list2.stream().forEach(temp->System.out.println(temp));//3、4、5、6、7



最后是两个有点复杂的无聊的例子,只为了说明链式调用可以写的很长很棒并且完成了许多内容,自信点~~~

List<PointsRace> teampoints = teams.stream().map(temp -> {
                                    List<Integer> point = getPoint(temp.getTeamId(), allmatch, win, lose, draw);
                                    return new PointsRace(temp.getTeamId(), temp, point.get(0), point.get(1), point.get(2), point.get(3), point.get(4), point.get(5));
                                }
                        ).sorted((p1, p2) -> {
                            if (p1.getPoint() != p2.getPoint()) {
                                return p2.getPoint() - p1.getPoint();
                            } else {
                                return p2.getGoalDifference() - p1.getGoalDifference();
                            }
                        }).collect(Collectors.toList());
List<CompetitionTeam> teams = Stream.of(competitionSection.getCompetitionSectionGroupteams().split(",")).filter(team -> team.length() > 0).map(team -> newsCompetitionMapper.getCompetitionTeam(Integer.parseInt(team))).collect(Collectors.toList());

另外的进阶内容别忘了我上面推荐的那个链接,比较详细的说。


以上~~









猜你喜欢

转载自blog.csdn.net/danengbinggan33/article/details/74518808