Java8函数式编程-包教包会系列(十)

作者:曹伟,叩丁狼教育高级讲师。原创文章,转载请注明出处。

详解Stream操作

操作步骤

使用Stream API操作数据可以分为以下几个步骤:

1)创建流:
通过数据源(如:集合、数组)获取流

2)处理流:(中的数据)
对流中的数据进行处理(处理是延迟执行的)

3)收集流:(中的数据)
通过调用收集方法,真正执行处理操作,并产生结果

创建流

创建一个流非常简单,有以下几种常用的方式:

1)Collection的默认方法stream()和parallelStream()
2)Arrays.stream()
3)Stream.of()
4)Stream.iterate()//迭代无限流(1, n->n +1)
5)Stream.generate()//生成无限流(Math::random)

代码实现

@Test
public void testCreateStream() throws Exception {
    // 1.Collection的默认方法stream()和parallelStream()
    List<String> list = Arrays.asList("a", "b", "c");
    Stream<String> stream = list.stream();// 获取顺序流
    Stream<String> parallelStream = list.parallelStream();

    // 2.Arrays.stream()
    IntStream intStream = Arrays.stream(new int[] { 1, 2, 3 });
    Stream<Integer> IntegerStream = Arrays.stream(new Integer[] { 1, 2, 3 });

    // 3.Stream.of()
    Stream<Integer> IntegerStream2 = Stream.of(1, 2, 3, 4);
    IntStream intStream2 = IntStream.of(1, 2, 3);

    // 4.Stream.iterate()//迭代无限流
    // Stream.iterate(1, n->n +1).forEach(System.out::println);
    Stream.iterate(1, n -> n + 1).limit(100).forEach(System.out::println);

    // 5.Stream.generate()//生成无限流
    // Stream.generate(Math::random).forEach(System.out::println);
    Stream.generate(Math::random).limit(2).forEach(System.out::println);
}

处理流

筛选和切片

filter(Predicate<T> p):过滤(根据传入的Lambda返回的ture/false 从流中过滤掉某些数据(筛选出某些数据))

distinct():去重(根据流中数据的 hashCode和 equals去除重复元素)
limit(long n):限定保留n个数据
skip(long n):跳过n个数据

图解:


image.png

image.png

代码实现

@Test
public void test1() throws Exception {
    Arrays.asList(1, 2, 1, 3, 3, 2, 4).stream().filter(i -> i % 2 == 0).forEach(System.out::println);
    System.out.println("================================================");
    Arrays.asList(1, 2, 1, 3, 3, 2, 4).stream().filter(i -> i % 2 == 0).distinct().forEach(System.out::println);
    System.out.println("================================================");
    Arrays.asList(1, 2, 1, 3, 3, 2, 4).stream().distinct().limit(2).forEach(System.out::println);
    System.out.println("================================================");
    Arrays.asList(1, 2, 1, 3, 3, 2, 4).stream().distinct().skip(2).forEach(System.out::println);
}

映射

映射
map(Function<T, R> f):接收一个函数作为参数,该函数会被应用到流中的每个元素上,并将其映射成一个新的元素。
flatMap(Function<T, Stream<R>> mapper):接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流

图解

image.png
image.png

代码实现

@Test
public void test3() throws Exception {
    System.out.println("=======================map=========================");
    Stream<String> stream = Stream.of("i","love","java");
    stream.map(s -> s.toUpperCase()).forEach(System.out::println);
    System.out.println("=======================flatMap========================");
    Stream<List<String>> stream2 = Stream.of(Arrays.asList("H","E"), Arrays.asList("L", "L", "O"));
    stream2.flatMap(list -> list.stream()).forEach(System.out::println);
}

排序

排序

sorted():自然排序使用Comparable<T>的int compareTo(T o)方法
sorted(Comparator<T> com):定制排序使用Comparator的int compare(T o1, T o2)方法

代码实现

@Test
public void test4() throws Exception {
    System.out.println("====================自然排序============================");
    Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().sorted().forEach(System.out::println);
    System.out.println("====================定制排序============================");
    Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().sorted((x,y) -> y.compareTo(x)).forEach(System.out::println);
}

收集流

查找匹配

allMatch:检查是否匹配所有元素
anyMatch:检查是否至少匹配一个元素
noneMatch:检查是否没有匹配的元素
findFirst:返回第一个元素(返回值为Optional<T>)
findAny:返回当前流中的任意元素(一般用于并行流)

备注:

Optional<T>是Java8新加入的一个容器,这个容器只存1个或0个元素,它用于防止出现NullpointException,它提供如下方法:

•isPresent()

判断容器中是否有值。

•ifPresent(Consume lambda)

容器若不为空则执行括号中的Lambda表达式。

•T get()

获取容器中的元素,若容器为空则抛出NoSuchElement异常。

•T orElse(T other)

获取容器中的元素,若容器为空则返回括号中的默认值。

代码实现

@Test
public void test5() throws Exception {
    System.out.println("======================检查是否匹配所有==========================");
    boolean allMatch = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().allMatch(x-> x>0);
    System.out.println(allMatch);
    System.out.println("======================检查是否至少匹配一个元素====================");
    boolean anyMatch = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().anyMatch(x -> x>7);
    System.out.println(anyMatch);
    System.out.println("======================检查是否没有匹配的元素======================");
    boolean noneMatch = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().noneMatch(x -> x >10);
    System.out.println(noneMatch);
    System.out.println("======================返回第一个元素==========================");
    Optional<Integer> first = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().findFirst();
    System.out.println(first.get()); 
    System.out.println("======================返回当前流中的任意元素=======================");
    Optional<Integer> any = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().findAny();
    System.out.println(any.get());
}

统计

count():返回流中元素的总个数
max(Comparator<T>):返回流中最大值
min(Comparator<T>):返回流中最小值

代码实现

@Test
public void test6() throws Exception {
    long count = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().count();
    System.out.println(count);
    Optional<Integer> max = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().max((x,y) -> x.compareTo(y));
    System.out.println(max.get());
    Optional<Integer> min = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().min((x,y) -> x.compareTo(y));
    System.out.println(min.get());
}

归约

reduce(T identity, BinaryOperator) / reduce(BinaryOperator) :将流中元素挨个结合起来,得到一个值。

图解

image.png

代码实现

@Test
public void test7() throws Exception {
    System.out.println("=====reduce:将流中元素反复结合起来,得到一个值==========");
    Stream<Integer> stream = Stream.iterate(1, x -> x+1).limit(100);
    //stream.forEach(System.out::println);
    Integer sum = stream.reduce(0,(x,y)-> x+y);
    System.out.println(sum);
}

汇总

reduce擅长的是生成一个值,如果想要从Stream生成一个集合或者Map等复杂的对象该怎么办呢?终极武器collect()横空出世!

collect(Collector<T, A, R>):将流转换为其他形式。

需求:

collect:将流转换为其他形式:list
collect:将流转换为其他形式:set
collect:将流转换为其他形式:TreeSet
collect:将流转换为其他形式:map
collect:将流转换为其他形式:sum
collect:将流转换为其他形式:avg
collect:将流转换为其他形式:max
collect:将流转换为其他形式:min

代码实现

@Test
public void test8() throws Exception {
    System.out.println("=====collect:将流转换为其他形式:list");
    List<Integer> list = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.toList());
    System.out.println(list);
    System.out.println("=====collect:将流转换为其他形式:set");
    Set<Integer> set = Arrays.asList(1, 1, 2, 2, 3, 3, 3).stream().collect(Collectors.toSet());
    System.out.println(set);
    System.out.println("=====collect:将流转换为其他形式:TreeSet");
    TreeSet<Integer> treeSet = Arrays.asList(1, 1, 2, 2, 3, 3, 3).stream().collect(Collectors.toCollection(TreeSet::new));
    System.out.println(treeSet);
    System.out.println("=====collect:将流转换为其他形式:map");
    Map<Integer, Integer> map = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.toMap(Integer::intValue, Integer::intValue));
    System.out.println(map);
    System.out.println("=====collect:将流转换为其他形式:sum");
    Integer sum = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.summingInt(Integer::intValue));
    System.out.println(sum);
    System.out.println("=====collect:将流转换为其他形式:avg");
    Double avg = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.averagingInt(Integer::intValue));
    System.out.println(avg);
    System.out.println("=====collect:将流转换为其他形式:max");
    Optional<Integer> max = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.maxBy(Integer::compareTo));
    System.out.println(max.get());
    System.out.println("=====collect:将流转换为其他形式:min");
    Optional<Integer> min = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.minBy((x,y) -> x-y));
    System.out.println(min.get());
}

分组和分区

Collectors.groupingBy()对元素做group操作。
Collectors.partitioningBy()对元素进行二分区操作。

图解

image.png
image.png

准备工作

private List<Product> products = new ArrayList<>();

@Before
public void init() {
    products.add(new Product(1L, "苹果手机", 8888.88,"手机"));//注意:要给Product类加一个分类名称dirName字段
    products.add(new Product(2L, "华为手机", 6666.66,"手机"));
    products.add(new Product(3L, "联想笔记本", 7777.77,"电脑"));
    products.add(new Product(4L, "机械键盘", 999.99,"键盘"));
    products.add(new Product(5L, "雷蛇鼠标", 222.22,"鼠标"));
}

需求

根据商品分类名称进行分组
根据商品价格范围多级分组
根据商品价格是否大于1000进行分区

代码实现

@Test
public void test9() throws Exception {
    System.out.println("=======根据商品分类名称进行分组==========================");
    Map<String, List<Product>> map = products.stream().collect(Collectors.groupingBy(Product::getDirName));
    System.out.println(map);
    System.out.println("=======根据商品价格范围多级分组==========================");
    Map<Double, Map<String, List<Product>>> map2 = products.stream().collect(Collectors.groupingBy(
            Product::getPrice, Collectors.groupingBy((p) -> {
                if (p.getPrice() > 1000) {
                    return "高级货";
                    } else {
                        return "便宜货";
                        }
                })));
    System.out.println(map2);

}
@Test
public void test10() throws Exception {
    System.out.println("========根据商品价格是否大于1000进行分区========================");
    Map<Boolean, List<Product>> map = products.stream().collect(Collectors.partitioningBy(p -> p.getPrice() > 1000));
    System.out.println(map);
}

总结

Streamvs Collection

虽然大部分情况下Stream是容器调用Collection.stream()方法得到的,但Stream和Collection有以下不同:

●无存储。Stream不是一种数据结构,它只是某种数据源的一个视图,数据源可以是一个数组,集合等。
●不修改。对Stream的任何修改都不会修改背后的数据源,比如过滤操作并不会删除被过滤的元素,而是产生一个新Stream。
●惰式执行。Stream上的操作并不会立即执行,只有等到用户真正需要结果的时候才会执行。
●可消费性。Stream只能被“消费”一次,一旦遍历过就会失效,就像容器的迭代器那样,想要再次遍历必须重新生成。

Stream分类

●中间操作(intermediate operations)
返回值为Stream的大都是中间操作,中间操作支持链式调用,并且会惰式执行

●终端操作(结束操作)(terminal operations)
返回值不为Stream 的为终端操作(立即求值),终端操作不支持链式调用,会触发实际计算

image.png
WechatIMG7.jpeg
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容

  • Jav8中,在核心类库中引入了新的概念,流(Stream)。流使得程序媛们得以站在更高的抽象层次上对集合进行操作。...
    仁昌居士阅读 3,561评论 0 6
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • Java8 in action 没有共享的可变数据,将方法和函数即代码传递给其他方法的能力就是我们平常所说的函数式...
    铁牛很铁阅读 1,146评论 1 2
  • “21世纪,我们先是学会了开车,然后是学会了show自己,再然后是学会了尊敬网络,而嘴角主义者则以为,凡事凡...
    泡芙兮阅读 119评论 0 1
  • 今天非常有幸在长沙参加了猫叔的干货分享会。 猫叔的分享分两个部分,在第一部分猫叔梳理了比特币和区块链行业的发展...
    大宏520阅读 199评论 0 2