分享

Java8-Stream使用实战

 ansatsing 2018-05-18

结合了我们自己的业务写了些简单的样例,绝大部分用到了Lamada表达式,也是Java8的新特性,看不懂的话先自己百度学习下;Stream有相当多的优势,函数式编程的方式条理非常清晰,很多复杂的计算,原来要十几行,现在只需要一行就能搞定,为了清晰,把每一个操作单独成一行了。

public class Post {
private long id;
private String title;
private boolean available;
private int readnum;
private String author;
private Type type;

public Post(long id, String title, boolean available, int readnum, Type type, String author) {
this.id = id;
this.title = title;
this.available = available;
this.readnum = readnum;
this.author = author;
this.type = type;
}

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public boolean isAvailable() {
return available;
}

public void setAvailable(boolean available) {
this.available = available;
}

public int getReadnum() {
return readnum;
}

public void setReadnum(int readnum) {
this.readnum = readnum;
}

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

public Type getType() {
return type;
}

public void setType(Type type) {
this.type = type;
}

public static enum Type {
FOOD,
CAR,
NEWS,
PET
}

}
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;

/**
 * Created by woody on 16/6/12.
 * PostExample
 */
public class PostExample {

    static List<Post> posts = Arrays.asList(
            new Post(1, "晒今天做的午餐", true, 25, Post.Type.FOOD, "张三"),
            new Post(2, "xx汽车现已上市", false, 10, Post.Type.CAR, "李雷"),
            new Post(3, "轮胎这样还能用么?", true, 30, Post.Type.CAR, "韩梅梅"),
            new Post(4, "G20最新筹备进展", true, 305, Post.Type.NEWS, "小明"),
            new Post(5, "端午节赛龙舟活动预告", true, 118, Post.Type.NEWS, "张三"),
            new Post(6, "你们家猫咪多久洗一次澡?", true, 56, Post.Type.PET, "小刚"),
            new Post(7, "这样的狗粮不要买", true, 98, Post.Type.PET, "李雷"),
            new Post(8, "教你选疫苗", false, 47, Post.Type.PET, "小红")
    );

    public static void main(String[] args) {

        /**
         * filter 过滤
         * 筛选出阅读数>100的帖子
         */
        List<Post> result1 = posts
                .stream()
                .filter(p -> p.getReadnum() > 100)
                .collect(Collectors.toList());

        /**
         * sorted 排序
         * 根据阅读数排序(从大到小)
         */
        List<Post> result2 = posts
                .stream()
                .sorted(Comparator
                        .comparing(Post::getReadnum)
                        .reversed())
                .collect(Collectors.toList());

        /**
         * map 映射
         * 获取所有标题
         */
        List<String> result3 = posts
                .stream()
                .map(Post::getTitle)
                .collect(Collectors.toList());

        /**
         * 截断 limit
         * 取前5篇帖子
         */
        List<Post> result4 = posts
                .stream()
                .limit(5)
                .collect(Collectors.toList());

        /**
         * distinct 区分
         * 获取所有作者,不重复
         */
        List<String> result5 = posts
                .stream()
                .map(Post::getAuthor)
                .distinct()
                .collect(Collectors.toList());

        /**
         * 跳过元素 skip
         * 跳过前3篇帖子
         */
        List<Post> result6 = posts
                .stream()
                .skip(3)
                .collect(Collectors.toList());

        /**
         * 任意一元素匹配 anyMatch
         * 是否有"小明"发的帖?
         */
        boolean result7 = posts
                .stream()
                .anyMatch(p -> p.getAuthor().equals("小明"));

        /**
         * 是否全部匹配 allMatch
         * 帖子是否阅读量都大于20?
         */
        boolean result8 = posts
                .stream()
                .allMatch(p -> p.getReadnum() > 20);

        /**
         * 全不匹配 noneMatch
         * 是否没有一个帖子是FOOD板块的?
         */
        boolean result9 = posts
                .stream()
                .noneMatch(p -> p.getType().equals(Post.Type.FOOD));

        /**
         * 查找任意一个符合要求的元素 finaAny
         * 查找一个News板块的帖子
         */
        Optional<Post> result10 = posts
                .stream()
                .filter(p -> p.getType().equals(Post.Type.NEWS))
                .findAny();

        /**
         * 查找第一个符合要求的元素 findFirst
         * 查找第一个阅读大于100的帖子的作者
         */
        Optional<String> result11 = posts
                .stream()
                .filter(p -> p.getReadnum() > 100)
                .map(Post::getAuthor)
                .findFirst();

        /**
         * 计数 count
         * 统计这些帖子作者的数量
         */
        long result12 = posts
                .stream()
                .map(Post::getAuthor)
                .distinct()
                .count();

        /**
         * 求这些帖子阅读总数
         */
        int result13 = posts
                .stream()
                .map(Post::getReadnum)
                .reduce(0, Integer::sum);

        //还可以这么写
        int result13_2 = posts
                .stream()
                .mapToInt(Post::getReadnum)
                .sum();

        /**
         * 阅读数最少的帖子的阅读数
         */
        int result14 = posts
                .stream()
                .map(Post::getReadnum)
                .reduce(0, Integer::min);

        /**
         * 阅读数最多未下架的帖子的作者
         */
        Optional<String> result15 = posts
                .stream()
                .filter(Post::isAvailable)
                .max(Comparator.comparing(Post::getReadnum).reversed())
                .map(Post::getAuthor);

        /**
         * 所有上架帖子,按阅读数从小到大
         */
        List<Post> result16 = posts
                .stream()
                .filter(Post::isAvailable)
                .sorted(Comparator.comparing(Post::getReadnum))
                .collect(Collectors.toList());

        /**
         * 李雷在哪些板块发过贴
         */
        List<Post.Type> result17 = posts
                .stream()
                .filter(p -> p.getAuthor().equals("李雷"))
                .map(Post::getType)
                .distinct()
                .collect(Collectors.toList());

        /**
         * 作者名单,用中文逗号隔开
         */
        String result18 = posts
                .stream()
                .map(Post::getAuthor)
                .distinct()
                .reduce("", ((s1, s2) -> s1 + "," + s2));

        /**
         * 把在宠物板块发广告帖(被下架贴)的人随便找一个出来
         */
        Optional<String> result19 = posts
                .stream()
                .filter(p -> !p.isAvailable())
                .filter(p -> p.getType().equals(Post.Type.PET))
                .map(Post::getAuthor)
                .findAny();

        /**
         * 计算张三在美食板块发的贴一共拿了多少点击
         */
        int result20 = posts
                .stream()
                .filter(p -> p.getAuthor().equals("张三"))
                .filter(p -> p.getType().equals(Post.Type.FOOD))
                .map(Post::getReadnum)
                .reduce(0, Integer::sum);

        /**
         * 把这些帖子按板块分组
         */
        Map<Post.Type, List<Post>> result21 = posts
                .stream()
                .collect(groupingBy(Post::getType));

        /**
         * 统计每个版块的帖子数
         */
        Map<Post.Type, Long> result22 = posts
                .stream()
                .collect(groupingBy(Post::getType, counting()));
    }
}
BigDecimal类型数据求和

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

public class TestLamada {
static List<Post> posts = Arrays.asList(
new Post(1, "晒今天做的午餐", true, new BigDecimal(25), Post.Type.FOOD, "张三"),
new Post(2, "xx汽车现已上市", false, new BigDecimal(10), Post.Type.CAR, "李雷"),
new Post(3, "轮胎这样还能用么?", true, new BigDecimal(30), Post.Type.CAR, "韩梅梅"),
new Post(4, "G20最新筹备进展", true, new BigDecimal(305), Post.Type.NEWS, "小明"),
new Post(5, "端午节赛龙舟活动预告", true, new BigDecimal(118), Post.Type.NEWS, "张三"),
new Post(6, "你们家猫咪多久洗一次澡?", true, new BigDecimal(56), Post.Type.PET, "小刚"),
new Post(7, "这样的狗粮不要买", true, new BigDecimal(98), Post.Type.PET, "李雷"),
new Post(8, "教你选疫苗", false, new BigDecimal(47), Post.Type.PET, "小红")
);
public static void main(String[] args) {
BigDecimal total = posts.stream().filter(post -> post.getAuthor().equals("张三")).map(Post::getReadnum).reduce(BigDecimal.ZERO,BigDecimal::add);
System.out.println(total);
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
引用于。 https://blog.csdn.net/wyd987100/article/details/51648241

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多