Java 8 集合 Stream

Java 8 是一个成功的版本,新增的内容很实用。比如大家熟悉的 lamda 表达式,集合的 Stream,等等。
本文讲讲 Stream 的使用。

Stream 是什么?

Stream 将要处理的集合看做流,然后方便的对流做操作,比如筛选,排序等等。

Stream 的操作可以分为两大类

  1. 中间操作。就是操作完还是返回一个流,还可以继续做其他操作。
  2. 终端操作。就是结束流,流结束之后就不可以再操作了,会返回一个值或者一个新的集合。

Stream 有以下特征

  1. 不改变源数据,会生成一个新的数据。
  2. 具有延迟执行特性,只有调用终端操作时,中间操作才会执行。

中间操作有:

  1. filter:筛选
  2. map/flatMap:映射
  3. sorted:排序
  4. distinct:去重
  5. limit:取前 n 个元素
  6. skip:跳过前 n 个元素
  7. ......

终端操作有:

  1. collect:收集
  2. foreach:遍历
  3. findFirst/findAny:获取单个元素
  4. anyMatch:判断是否有满足条件的元素
  5. reduce:归约
  6. max、min、count:统计
  7. ......

创建 Stream

  1. 通过集合的 stream() 或者 parallelStream() 方法创建
List<String> list = Arrays.asList("a", "b", "c");
// 创建一个顺序流
Stream<String> stream = list.stream();
// 创建一个并行流
Stream<String> parallelStream = list.parallelStream();

stream() 创建的是顺序流,由主线程按顺序对流执行操作。
parallelStream() 创建的是并行流,如果对顺序没有要求,可以使用它以多线程并行执行。数据量比较大的时候并行流可以明显提高效率。

  1. 使用 java.util.Arrays.stream(T[] array) 方法用数组创建流
int[] array={1,2,3,4,5};
IntStream stream = Arrays.stream(array);
  1. 使用 Stream 的静态方法:of()、iterate()、generate()
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
Stream<Integer> stream2 = Stream.iterate(0, (x) -> x + 3).limit(4);
Stream<Double> stream3 = Stream.generate(Math::random).limit(3);

中间操作

filter

传入规则,筛选出符合要求的元素。

filter

例子1(筛选出大于 3 的元素)

Arrays.asList(1, 2, 3, 4, 5).stream()
        .filter(x -> x > 3)
        .forEach(System.out::println);

结果:

4
5

例子2(筛选出年龄大于 20 的人的姓名)

List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Jack", 10, "男"));
personList.add(new Person("Rose", 15, "女"));
personList.add(new Person("Tom", 20, "男"));
personList.add(new Person("Lucy", 25, "女"));
personList.add(new Person("Lily", 39, "女"));

personList.stream()
        .filter(person -> person.getAge() > 20)
        .map(Person::getName)
        .forEach(System.out::println);

结果:

Lucy
Lily

map、flatMap

用于映射。

  • map:接收一个函数作为参数,按照一定的规则将元素映射为一个新的元素。


    map
  • flatMap:接收一个函数作为参数,按照一定的规则将每个元素映射为一个新的流,然后把所有流连接成一个流。


    flatMap

例子1(将每个数映射为它的平方)

Arrays.asList(1, 2, 3).stream()
        .map(i -> i*i)
        .forEach(System.out::println);

结果

1
4
9

例子2(将筛选出的年龄大于 20 的 Person 对象映射为 name 属性)

List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Jack", 10, "男"));
personList.add(new Person("Rose", 15, "女"));
personList.add(new Person("Tom", 20, "男"));
personList.add(new Person("Lucy", 25, "女"));
personList.add(new Person("Lily", 39, "女"));

personList.stream()
        .filter(person -> person.getAge() > 20)
        .map(Person::getName)
        .forEach(System.out::println);

结果:

Lucy
Lily

例子3(将每个元素转化为一个流,然后合并)

List<String> newList = Arrays.asList("a,b,c", "d,e,f,g").stream()
        .flatMap(s -> Arrays.stream(s.split(",")))
        .collect(Collectors.toList());
System.out.println(newList);

结果:

[a, b, c, d, e, f, g]

sorted

排序。

例子1:

List<Integer> sortedList = Arrays.asList(4, 7, 3, 9, 1, 5).stream()
        .sorted(Integer::compareTo)
        .collect(Collectors.toList());
System.out.println(sortedList);

sortedList = Arrays.asList(4, 7, 3, 9, 1, 5).stream()
        .sorted() // 默认升序
        .collect(Collectors.toList());
System.out.println(sortedList);

结果:

[1, 3, 4, 5, 7, 9]
[1, 3, 4, 5, 7, 9]

例子2:

List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Lucy", 25, "女", 2));
personList.add(new Person("Rose", 15, "女", 1));
personList.add(new Person("Jack", 10, "男", 1));
personList.add(new Person("Tom", 20, "男", 2));
personList.add(new Person("Tony", 35, "男", 3));
personList.add(new Person("Lily", 30, "女", 3));

// 按年龄排序(升序)
List<String> nameSortedByAge = personList.stream()
        .sorted(Comparator.comparing(Person::getAge))
        .map(Person::getName)
        .collect(Collectors.toList());
System.out.println(nameSortedByAge);

// 按年龄排序(倒序,加 reversed)
nameSortedByAge = personList.stream()
        .sorted(Comparator.comparing(Person::getAge).reversed())
        .map(Person::getName)
        .collect(Collectors.toList());
System.out.println(nameSortedByAge);

// 先按性别再按年龄排序
nameSortedByAge = personList.stream()
        .sorted(Comparator.comparing(Person::getSex).thenComparing(Person::getAge))
        .map(Person::getName)
        .collect(Collectors.toList());
System.out.println(nameSortedByAge);

// 先按性别再按年龄自定义排序(倒序)
nameSortedByAge = personList.stream()
        .sorted((p1, p2) -> {
            if (p1.getSex().equals(p2.getSex())) {
                return p2.getAge() - p1.getAge();
            } else {
                return p2.getSex().compareTo(p1.getSex());
            }
        })
        .map(Person::getName)
        .collect(Collectors.toList());
System.out.println(nameSortedByAge);

结果:

[Jack, Rose, Tom, Lucy, Lily, Tony]
[Tony, Lily, Lucy, Tom, Rose, Jack]
[Rose, Lucy, Lily, Jack, Tom, Tony]
[Tony, Tom, Jack, Lily, Lucy, Rose]

distinct

去重。

例子1:

String[] arr1 = { "a", "b", "c", "d" };
String[] arr2 = { "d", "e", "f", "g" };
List<String> newList = Stream.concat(Stream.of(arr1), Stream.of(arr2))
        .distinct()
        .collect(Collectors.toList());
System.out.println(newList);

结果:

[a, b, c, d, e, f, g]

例子2:
对象去重

List<Person> personList = new ArrayList<Person>();
personList.add(new Person(1001, "Lucy", 25, "女", 2));
personList.add(new Person(1001, "Lucy", 25, "女", 2));
personList.add(new Person(1002,"Rose", 15, "女", 1));
personList.add(new Person(1003,"Jack", 10, "男", 1));

List<String> names = personList.stream()
        .filter(distinctByKey(Person::getId))
        .map(Person::getName)
        .collect(Collectors.toList());
System.out.println(names);

static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Map<Object, Boolean> seen = new ConcurrentHashMap<>();
    return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}

结果:

[Lucy, Rose, Jack]

limit

限制从集合中取前 n 位

List<Integer> limitList = Stream.iterate(1, x -> x + 2)
        .limit(10)
        .collect(Collectors.toList());
System.out.println(limitList);

结果:

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

skip

跳过前 n 位

List<Integer> limitList = Stream.iterate(1, x -> x + 2)
        .skip(1)
        .limit(10)
        .collect(Collectors.toList());
System.out.println(limitList);

结果:

[3, 5, 7, 9, 11, 13, 15, 17, 19, 21]

终端操作

forEach

Arrays.asList(1, 2, 3, 4, 5).stream()
        .forEach(System.out::println);

结果:

1
2
3
4
5

findFirst

System.out.println(Arrays.asList(1, 2, 3, 4, 5).stream()
        .filter(x -> x > 3)
        .findFirst()
        .get());

结果:

4

findAny

获取任意一个

// findAny 获取任意适用于并行流 parallelStream
System.out.println(Arrays.asList(1, 2, 3, 4, 5).parallelStream()
        .filter(x -> x > 3)
        .findAny()
        .get());

结果:

4 或者 5

anyMatch

是否有满足条件的元素

System.out.println(Arrays.asList(1, 2, 3, 4, 5).stream()
       .anyMatch(x -> x > 3));

reduce

归纳。也称缩减,顾名思义,是把一个流缩减成一个值,用与集合求和、求乘积、求最值等。

求和:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);

// 求和方式 1
int sum = list.stream()
        .reduce((x, y) -> x + y)
        .get();
System.out.println(sum);
// 求和方式 2
sum = list.stream()
        .reduce(Integer::sum)
        .get();
System.out.println(sum);
// 求和方式 3
// 列表中所有元素和要再加上第一个参数
sum = list.stream()
        .reduce(1, Integer::sum);
System.out.println(sum);

结果:

21
21
22

求乘积:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);

// 求乘积
int product = list.stream()
        .reduce((x, y) -> x * y)
        .get();
System.out.println(product);

结果:

720

求最大值:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);

// 求最大值方式 1
int maxvalue = list.stream()
        .reduce((x, y) -> x > y ? x : y)
        .get();
System.out.println(maxvalue);
// 求最大值方式 2
// 列表的最大值和第一个参数再选一个最大值
maxvalue = list.stream()
        .reduce(10, Integer::max);
System.out.println(maxvalue);

结果:

6
10

max、min、count

用于对集合进行统计

// 统计最大值是什么
// 打印 3
int maxValue = Arrays.asList(1, 2, 3).stream()
        .max(Integer::compareTo)
        .get();
System.out.println(maxValue);

// 统计最长的字符串是什么
// 打印 ccc
String maxLengthValue = Arrays.asList("a", "bb", "ccc").stream()
        .max(Comparator.comparing(String::length))
        .get();
System.out.println(maxLengthValue);
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Jack", 10, "男"));
personList.add(new Person("Rose", 15, "女"));
personList.add(new Person("Tom", 20, "男"));
personList.add(new Person("Lucy", 25, "女"));
personList.add(new Person("Lily", 39, "女"));

// 统计年龄最小的人的姓名
// 打印 Jack
String name = personList.stream()
        .min(Comparator.comparingInt(Person::getAge))
        .map(Person::getName)
        .get();
System.out.println(name);
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Jack", 10, "男"));
personList.add(new Person("Rose", 15, "女"));
personList.add(new Person("Tom", 20, "男"));
personList.add(new Person("Lucy", 25, "女"));
personList.add(new Person("Lily", 39, "女"));

// 统计男生的人数
// 打印 2
long count = personList.stream()
        .filter(person -> person.getSex().equals("男"))
        .count();
System.out.println(count);

collect

把流收集起来,可以收集成一个新的集合,也可以收集成一个值。

例子1:toList、toSet、toMap
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 5, 6, 6);

// 转化为 List
List<Integer> newList = list.stream()
        .filter(x -> x > 2)
        .collect(Collectors.toList());
System.out.println(newList);

// 转化为 Set
Set<Integer> set = list.stream()
        .filter(x -> x > 2)
        .collect(Collectors.toSet());
System.out.println(set);

List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Jack", 10, "男"));
personList.add(new Person("Rose", 15, "女"));
personList.add(new Person("Tom", 20, "男"));
personList.add(new Person("Lucy", 25, "女"));
personList.add(new Person("Lily", 39, "女"));

// 转化为 Mao
Map<String, Person> map = personList.stream()
        .filter(person -> person.getAge() > 20)
        .collect(Collectors.toMap(Person::getName, person -> person));
System.out.println(map);

结果:

[3, 4, 5, 5, 6, 6]
[3, 4, 5, 6]
{Lucy=Person@1ddc4ec2, Lily=Person@133314b}

另外如果想转化为 LinkedList 的话,collect 的参数设为 Collectors.toCollection(LinkedList::new)

例子2:各种统计方法
  • 计数:count
  • 平均值:averagingInt、averagingLong、averagingDouble
  • 最值:maxBy、minBy
  • 求和:summingInt、summingLong、summingDouble
  • 统计以上所有:summarizingInt、summarizingLong、summarizingDouble
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Jack", 10, "男"));
personList.add(new Person("Rose", 15, "女"));
personList.add(new Person("Tom", 20, "男"));
personList.add(new Person("Lucy", 25, "女"));
personList.add(new Person("Lily", 39, "女"));

// 求总数
long count = personList.stream()
    .collect(Collectors.counting());
System.out.println(count);
// 求平均年龄
double averageAge = personList.stream()
    .collect(Collectors.averagingInt(Person::getAge));
System.out.println(averageAge);
// 求最高年龄
int maxAge = personList.stream()
    .map(Person::getAge)
    .collect(Collectors.maxBy(Integer::compare))
    .get();
System.out.println(maxAge);
// 求年龄之和
Integer sum = personList.stream()
    .collect(Collectors.summingInt(Person::getAge));
System.out.println(sum);
// 一次性统计所有信息
DoubleSummaryStatistics all = personList.stream()
    .collect(Collectors.summarizingDouble(Person::getAge));
System.out.println(all);
例子3:分组

partitioningBy:分成两部分
groupingBy:分成多部分

List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Jack", 10, "男", 1));
personList.add(new Person("Rose", 15, "女", 1));
personList.add(new Person("Tom", 20, "男", 2));
personList.add(new Person("Lucy", 25, "女", 2));
personList.add(new Person("Lily", 30, "女", 3));
personList.add(new Person("Tony", 35, "女", 3));
personList.add(new Person("未知", 100, "未知", 4));

// 按年龄是否大于 20 分组
Map<Boolean, List<Person>> part = personList.stream()
        .collect(Collectors.partitioningBy(person -> person.getAge() > 20));
System.out.println(part);

// 按性别分组
Map<String, List<Person>> group = personList.stream()
        .collect(Collectors.groupingBy(Person::getSex));
System.out.println(group);

// 先按班级分组,再按性别分组
Map<Integer, Map<String, List<Person>>> group2 = personList.stream()
        .collect(Collectors.groupingBy(Person::getClazz, Collectors.groupingBy(Person::getSex)));
System.out.println(group2);

结果:

{false=[Person@5b6f7412, Person@27973e9b, Person@312b1dae], true=[Person@7530d0a, Person@27bc2616, Person@3941a79c, Person@506e1b77]}
{女=[Person@27973e9b, Person@7530d0a, Person@27bc2616, Person@3941a79c], 未知=[Person@506e1b77], 男=[Person@5b6f7412, Person@312b1dae]}
{1={女=[Person@27973e9b], 男=[Person@5b6f7412]}, 2={女=[Person@7530d0a], 男=[Person@312b1dae]}, 3={女=[Person@27bc2616, Person@3941a79c]}, 4={未知=[Person@506e1b77]}}
例子4:joining

将 stream 中的元素用特定的连接符连接成一个字符串。

List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Jack", 10, "男", 1));
personList.add(new Person("Rose", 15, "女", 1));
personList.add(new Person("Tom", 20, "男", 2));
personList.add(new Person("Lucy", 25, "女", 2));
personList.add(new Person("Lily", 30, "女", 3));
personList.add(new Person("Tony", 35, "女", 3));

String names = personList.stream()
        .map(Person::getName)
        .collect(Collectors.joining(", "));
System.out.println(names);

结果:

Jack, Rose, Tom, Lucy, Lily, Tony
例子5:reducing

归约。相比于 stream 本身的 reduce 方法,增加了对自定义归约的支持。

List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Jack", 10, "男", 1));
personList.add(new Person("Rose", 15, "女", 1));
personList.add(new Person("Tom", 20, "男", 2));
personList.add(new Person("Lucy", 25, "女", 2));
personList.add(new Person("Lily", 30, "女", 3));
personList.add(new Person("Tony", 35, "女", 3));

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

推荐阅读更多精彩内容