Stream流基本使用

1. 概述

  • Java8的Stream使用的是函数式编程模式,如同它的名字一样,它可以被用来对集合或数组进行链状流式的操作。可以更方便的让我们对集合或数组操作

  • 案例如下

xml 复制代码
<dependencies>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.16</version>
    </dependency>
</dependencies>
java 复制代码
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode//用于后期的去重使用
public class Author {
    //id
    private Long id;
    //姓名
    private String name;
    //年龄
    private Integer age;
    //简介
    private String intro;
    //作品
    private List<Book> books;
}
java 复制代码
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode//用于后期的去重使用
public class Book {
    //id
    private Long id;
    //书名
    private String name;

    //分类
    private String category;

    //评分
    private Integer score;

    //简介
    private String intro;

}
java 复制代码
public class StreamDemo01 {

    public static void main(String[] args) {
		// 输出:
		
    }

    private static List<Author> getAuthors() {
        //数据初始化
        Author author = new Author(1L, "蒙多", 33, "一个从菜刀中明悟哲理的祖安人", null);
        Author author2 = new Author(2L, "亚拉索", 15, "狂风也追逐不上他的思考速度", null);
        Author author3 = new Author(3L, "易", 14, "是这个世界在限制他的思维", null);
        Author author4 = new Author(3L, "易", 14, "是这个世界在限制他的思维", null);

        //书籍列表
        List<Book> books1 = new ArrayList<>();
        List<Book> books2 = new ArrayList<>();
        List<Book> books3 = new ArrayList<>();

        books1.add(new Book(1L, "刀的两侧是光明与黑暗", "哲学,爱情", 88, "用一把刀划分了爱恨"));
        books1.add(new Book(2L, "一个人不能死在同一把刀下", "个人成长,爱情", 99, "讲述如何从失败中明悟真理"));

        books2.add(new Book(3L, "那风吹不到的地方", "哲学", 85, "带你用思维去领略世界的尽头"));
        books2.add(new Book(3L, "那风吹不到的地方", "哲学", 85, "带你用思维去领略世界的尽头"));
        books2.add(new Book(4L, "吹或不吹", "爱情,个人传记", 56, "一个哲学家的恋爱观注定很难把他所在的时代理解"));

        books3.add(new Book(5L, "你的剑就是我的剑", "爱情", 56, "无法想象一个武者能对他的伴侣这么的宽容"));
        books3.add(new Book(6L, "风与剑", "个人传记", 100, "两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));
        books3.add(new Book(6L, "风与剑", "个人传记", 100, "两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));

        author.setBooks(books1);
        author2.setBooks(books2);
        author3.setBooks(books3);
        author4.setBooks(books3);

        List<Author> authorList = new ArrayList<>(Arrays.asList(author, author2, author3, author4));
        return authorList;
    }

}

2. 快速入门

2.1 需求

  • 调用getAuthors方法获取到作家的集合。现在需要打印所有年龄小于18的作家的名字,并且要注意去重。

2.2 实现

java 复制代码
List<Author> authors = getAuthors();
authors.stream() // 把集合转换成流
    .distinct() // 去重
    .filter(new Predicate<Author>() {
        @Override
        public boolean test(Author author) {
            return author.getAge() < 18;
        }
    })
    .forEach(new Consumer<Author>() {
        @Override
        public void accept(Author author) {
            System.out.println(author.getName());
        }
    });

System.out.println(authors);
  • 替换成 lamda 后:
java 复制代码
//打印所有年龄小于18的作家的名字,并且要注意去重
List<Author> authors = getAuthors();
authors.stream()//把集合转换成流
       .distinct()//先去除重复的作家
       .filter(author -> author.getAge()<18)//筛选年龄小于18的
       .forEach(author -> System.out.println(author.getName()));//遍历打印名字

3. 常用操作

3.1 创建流

单列集合: 集合对象.stream()

java 复制代码
List<Author> authors = getAuthors();
Stream<Author> stream = authors.stream();
  • 数组:Arrays.stream(数组) 或者使用Stream.of来创建
java 复制代码
Integer[] arr = {1,2,3,4,5};
Stream<Integer> stream = Arrays.stream(arr);
Stream<Integer> stream2 = Stream.of(arr);
  • 举例:
java 复制代码
public static void main(String[] args) {
    Integer[] arr = {1, 2, 3, 4, 5};
    Stream<Integer> stream = Arrays.stream(arr);
    stream.distinct().filter(new Predicate<Integer>() {
        @Override
        public boolean test(Integer integer) {
            return integer > 2;
        }
    }).forEach(new Consumer<Integer>() {
        @Override
        public void accept(Integer integer) {
            System.out.println(integer);
        }
    });
}
  • 转换成 Lambad 表达式后:
java 复制代码
public static void main(String[] args) {
    Integer[] arr = {1, 2, 3, 4, 5};
    Stream<Integer> stream = Arrays.stream(arr);
    stream.distinct().filter(integer -> integer > 2).forEach(integer -> System.out.println(integer));
}
  • 也可以使用 Stream.of 方法
java 复制代码
Stream<Integer> stream2 = Stream.of(arr);
stream2.distinct().filter(integer -> integer > 2).forEach(integer -> System.out.println(integer));

双列集合:转换成单列集合后再创建

java 复制代码
Map<String,Integer> map = new HashMap<>();
map.put("蜡笔小新",19);
map.put("黑子",17);
map.put("日向翔阳",16);

Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
Stream<Map.Entry<String, Integer>> stream = entrySet.stream();
stream.filter(new Predicate<Map.Entry<String, Integer>>() {
    @Override
    public boolean test(Map.Entry<String, Integer> entry) {
        return entry.getValue() > 16;
    }
}).forEach(new Consumer<Map.Entry<String, Integer>>() {
    @Override
    public void accept(Map.Entry<String, Integer> entry) {
        System.out.println(entry.getKey() + "===" + entry.getValue());
    }
});
  • 替换成 Lambda 表达式
java 复制代码
Map<String,Integer> map = new HashMap<>();
map.put("蜡笔小新",19);
map.put("黑子",17);
map.put("日向翔阳",16);

Stream<Map.Entry<String, Integer>> stream = map.entrySet().stream();
stream.filter(entry -> entry.getValue() > 16).forEach(
entry -> System.out.println(entry.getKey() + "===" + entry.getValue()));

3.2 中间操作

3.2.1 filter

  • 可以对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中。
  • 例如:打印所有姓名长度大于1的作家的姓名
java 复制代码
List<Author> authors = getAuthors();
// 打印所有姓名长度大于1的作家姓名
authors.stream().filter(new Predicate<Author>() {
    @Override
    public boolean test(Author author) {
        return author.getName().length() > 1;
    }
}).forEach(new Consumer<Author>() {
    @Override
    public void accept(Author author) {
        System.out.println(author.getName());
    }
});
  • 替换成 Lambda 表达式
java 复制代码
List<Author> authors = getAuthors();
authors.stream().filter(author -> author.getName().length() > 1)
    .forEach(author -> System.out.println(author.getName()));

3.2.2 map

  • 可以把对流中的元素进行计算或转换。
java 复制代码
List<Author> authors = getAuthors();
authors.stream().map(new Function<Author, String>() {
    @Override
    public String apply(Author author) {
        return author.getName();
    }
}).
forEach(new Consumer<String>() {
    @Override
    public void accept(String s) {
        System.out.println(s);
    }
});
  • 转换后
java 复制代码
// 打印所有作家的姓名
List<Author> authors = getAuthors();
authors.stream().map(author -> author.getName())
    .forEach(name -> System.out.println(name));
  • 计算:所有年龄加10
java 复制代码
List<Author> authors = getAuthors();
authors.stream()
.map(author -> author.getAge())
.map(age->age+10)
.forEach(age-> System.out.println(age));

3.2.3 distinct

  • 可以去除流中的重复元素。

  • 例如:打印所有作家的姓名,并且要求其中不能有重复元素。

java 复制代码
List<Author> authors = getAuthors();
authors.stream().distinct().forEach(author -> System.out.println(author.getName()));
  • 注意:distinct方法是依赖Object的equals方法来判断是否是相同对象的。所以需要注意重写equals方法。

3.2.4 sorted

  • 可以对流中的元素进行排序。

例如:对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素。

java 复制代码
List<Author> authors = getAuthors();
// 对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素
authors.stream()
    .distinct()
    .sorted()
    .forEach(author -> System.out.println(author.getAge()));

注意 :如果调用空参的sorted()方法,需要流中的元素是实现了Comparable

  • 实现 Comparable 接口
java 复制代码
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode//用于后期的去重使用
public class Author implements Comparable<Author> {
    //id
    private Long id;
    //姓名
    private String name;
    //年龄
    private Integer age;
    //简介
    private String intro;
    //作品
    private List<Book> books;

    @Override
    public int compareTo(Author o) {
        return o.getAge() - this.getAge();
    }
}
java 复制代码
public static void test8() {
List<Author> authors = getAuthors();
// 对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素
authors.stream()
    .distinct()
    .sorted(new Comparator<Author>() {
        @Override
        public int compare(Author o1, Author o2) {
            return o2.getAge() - o1.getAge();
        }
    })
    .forEach(author -> System.out.println(author.getAge()));
}
  • 简化后:
java 复制代码
public static void test8() {
List<Author> authors = getAuthors();
// 对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素
authors.stream()
    .distinct()
    .sorted((o1, o2) -> o2.getAge() - o1.getAge())
    .forEach(author -> System.out.println(author.getAge()));
}

3.2.5 limit

  • 可以设置流的最大长度,超出的部分将被抛弃。

例如:对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素,然后打印其中年龄最大的两个作家的姓名。

java 复制代码
List<Author> authors = getAuthors();
authors.stream()
    .distinct()
    .sorted()
    .limit(2)
    .forEach(author -> System.out.println(author.getAge()));

3.2.6 skip

  • 跳过流中的前n个元素,返回剩下的元素

例如:打印除了年龄最大的作家外的其他作家,要求不能有重复元素,并且按照年龄降序排序。

java 复制代码
List<Author> authors = getAuthors();
authors.stream()
    .distinct()
    .sorted()
    .skip(1)
    .forEach(author -> System.out.println(author.getName()));

3.2.7 flatMap

  • map 只能把一个对象转换成另一个对象来作为流中的元素。而flatMap可以把一个对象转换成多个对象作为流中的元素。

例一:打印所有书籍的名字。要求对重复的元素进行去重。

java 复制代码
// 打印所有书籍的名字。要求对重复的元素进行去重。
List<Author> authors = getAuthors();
authors.stream()
.flatMap(new Function<Author, Stream<Book>>() {
    @Override
    public Stream<Book> apply(Author author) {
        return author.getBooks().stream();
    }
})
.distinct()
.forEach(new Consumer<Book>() {
    @Override
    public void accept(Book book) {
        System.out.println(book.getName());
    }
});
  • 简化后
java 复制代码
// 打印所有书籍的名字。要求对重复的元素进行去重。
List<Author> authors = getAuthors();
authors.stream()
    .flatMap(author -> author.getBooks().stream())
    .distinct()
    .forEach(book -> System.out.println(book.getName()));

例二:打印现有数据的所有分类。要求对分类进行去重。 不能出现这种格式:哲学,爱情

java 复制代码
// 打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式:哲学,爱情
List<Author> authors = getAuthors();
authors.stream()
    .flatMap(author -> author.getBooks().stream())
    .distinct()
    .flatMap(book -> Arrays.stream(book.getCategory().split(",")))
    .distinct()
    .forEach(category -> System.out.println(category));

3.3 终结操作

3.3.1 forEach

  • 对流中的元素进行遍历操作,我们通过传入的参数去指定对遍历到的元素进行什么具体操作。

例子:输出所有作家的名字

java 复制代码
// 输出所有作家的名字
List<Author> authors = getAuthors();
authors.stream()
.map(author -> author.getName())
.distinct()
.forEach(name -> System.out.println(name));

3.3.2 count

  • 可以用来获取当前流中元素的个数。

例子:打印这些作家的所出书籍的数目,注意删除重复元素。

java 复制代码
// 打印这些作家的所出书籍的数目,注意删除重复元素。
List<Author> authors = getAuthors();
long count = authors.stream().flatMap(author -> author.getBooks().stream()).distinct().count();
System.out.println(count);

3.3.3 max&min

  • 可以用来或者流中的最值。

例子:分别获取这些作家的所出书籍的最高分和最低分并打印。

java 复制代码
// 分别获取这些作家的所出书籍的最高分和最低分并打印。
//Stream<Author>  -> Stream<Book> ->Stream<Integer>  ->求值

List<Author> authors = getAuthors();
Optional<Integer> max = authors.stream()
    .flatMap(author -> author.getBooks().stream())
    .map(book -> book.getScore())
    .max((score1, score2) -> score1 - score2);

Optional<Integer> min = authors.stream()
    .flatMap(author -> author.getBooks().stream())
    .map(book -> book.getScore())
    .min((score1, score2) -> score1 - score2);
System.out.println(max.get());
System.out.println(min.get());

3.3.4 collect

  • 把当前流转换成一个集合。

例子:获取一个存放所有作者名字的List集合。

java 复制代码
// 获取一个存放所有作者名字的List集合。
List<Author> authors = getAuthors();
List<String> nameList = authors.stream()
    .map(author -> author.getName())
    .collect(Collectors.toList());
System.out.println(nameList);
  • 获取一个所有书名的Set集合。
java 复制代码
// 获取一个所有书名的Set集合。
List<Author> authors = getAuthors();
Set<Book> books = authors.stream()
    .flatMap(author -> author.getBooks().stream())
    .collect(Collectors.toSet());
System.out.println(books);
java 复制代码
[Book(id=4, name=吹或不吹, category=爱情,个人传记, score=56, intro=一个哲学家的恋爱观注定很难把他所在的时代理解), Book(id=6, name=风与剑, category=个人传记, score=100, intro=两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?), Book(id=2, name=一个人不能死在同一把刀下, category=个人成长,爱情, score=99, intro=讲述如何从失败中明悟真理), Book(id=3, name=那风吹不到的地方, category=哲学, score=85, intro=带你用思维去领略世界的尽头), Book(id=5, name=你的剑就是我的剑, category=爱情, score=56, intro=无法想象一个武者能对他的伴侣这么的宽容), Book(id=1, name=刀的两侧是光明与黑暗, category=哲学,爱情, score=88, intro=用一把刀划分了爱恨)]
  • 获取一个Map集合,mapkey为作者名,valueList<Book>
java 复制代码
// 获取一个Map集合,map的key为作者名,value为List<Book>
List<Author> authors = getAuthors();
Map<String, List<Book>> map = authors.stream()
    .distinct()
    .collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));
System.out.println(map);
java 复制代码
{亚拉索=[Book(id=3, name=那风吹不到的地方, category=哲学, score=85, intro=带你用思维去领略世界的尽头), Book(id=3, name=那风吹不到的地方, category=哲学, score=85, intro=带你用思维去领略世界的尽头), Book(id=4, name=吹或不吹, category=爱情,个人传记, score=56, intro=一个哲学家的恋爱观注定很难把他所在的时代理解)], 蒙多=[Book(id=1, name=刀的两侧是光明与黑暗, category=哲学,爱情, score=88, intro=用一把刀划分了爱恨), Book(id=2, name=一个人不能死在同一把刀下, category=个人成长,爱情, score=99, intro=讲述如何从失败中明悟真理)], 易=[Book(id=5, name=你的剑就是我的剑, category=爱情, score=56, intro=无法想象一个武者能对他的伴侣这么的宽容), Book(id=6, name=风与剑, category=个人传记, score=100, intro=两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?), Book(id=6, name=风与剑, category=个人传记, score=100, intro=两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?)]}

3.6 查找与匹配

3.6.1 anyMatch

  • 可以用来判断是否有任意符合匹配条件的元素,结果为boolean类型。

例子:判断是否有年龄在29以上的作家

java 复制代码
// 判断是否有年龄在29以上的作家
List<Author> authors = getAuthors();
boolean flag = authors.stream()
    .anyMatch(author -> author.getAge() > 29);
System.out.println(flag);

3.6.2 allMatch

  • 可以用来判断是否都符合匹配条件,结果为boolean类型。如果都符合结果为true,否则结果为false。

例子:判断是否所有的作家都是成年人

java 复制代码
// 断是否所有的作家都是成年人
List<Author> authors = getAuthors();
boolean flag = authors.stream()
    .allMatch(author -> author.getAge() >= 18);
System.out.println(flag);

3.6.3 noneMatch

  • 可以判断流中的元素是否都不符合匹配条件。如果都不符合结果为true,否则结果为false

例子:判断作家是否都没有超过100岁的。

java 复制代码
// 判断作家是否都没有超过100岁的。
List<Author> authors = getAuthors();
boolean b = authors.stream()
    .noneMatch(author -> author.getAge() > 100);
System.out.println(b);

3.6.4 findAny

  • 获取流中的任意一个元素。该方法没有办法保证获取的一定是流中的第一个元素。

例子:获取任意一个年龄大于18的作家,如果存在就输出他的名字

java 复制代码
// 获取任意一个年龄大于18的作家,如果存在就输出他的名字
List<Author> authors = getAuthors();
Optional<Author> optionalAuthor = authors.stream()
   .filter(author -> author.getAge()>18)
   .findAny();

optionalAuthor.ifPresent(author -> System.out.println(author.getName()));

3.6.5 findFirst

  • 获取流中的第一个元素。

例子:获取一个年龄最小的作家,并输出他的姓名。

java 复制代码
// 获取一个年龄最小的作家,并输出他的姓名。
List<Author> authors = getAuthors();
Optional<Author> first = authors.stream()
    .sorted((o1, o2) -> o1.getAge() - o2.getAge())
    .findFirst();
first.ifPresent(author -> System.out.println(author.getName()));

3.6.6 reduce归并

  • 对流中的数据按照你指定的计算方式计算出一个结果。(缩减操作)

  • reduce的作用是把stream中的元素给组合起来,我们可以传入一个初始值,它会按照我们的计算方式依次拿流中的元素和初始化值进行计算,计算结果再和后面的元素计算。

  • reduce两个参数的重载形式内部的计算方式如下:

java 复制代码
T result = identity;
for (T element : this stream)
	result = accumulator.apply(result, element)
return result;
  • 其中identity就是我们可以通过方法参数传入的初始值,accumulator的apply具体进行什么计算也是我们通过方法参数来确定的。

例子:使用reduce求所有作者年龄的和

java 复制代码
// 使用reduce求所有作者年龄的和
List<Author> authors = getAuthors();
Integer sum = authors.stream()
    .distinct()
    .map(author -> author.getAge())
    .reduce(0, (result, element) -> result + element);
System.out.println(sum);
  • 使用reduce求所有作者中年龄的最大值
java 复制代码
// 使用reduce求所有作者中年龄的最大值
List<Author> authors = getAuthors();
Integer max = authors.stream()
    .map(author -> author.getAge())
    .reduce(Integer.MIN_VALUE, (result, element) -> result < element ? element : result);

System.out.println(max);
  • 使用reduce求所有作者中年龄的最小值
java 复制代码
// 使用reduce求所有作者中年龄的最小值
List<Author> authors = getAuthors();
Integer min = authors.stream()
    .map(author -> author.getAge())
    .reduce(Integer.MAX_VALUE, (result, element) -> result > element ? element : result);
System.out.println(min);
  • reduce一个参数的重载形式内部的计算
java 复制代码
boolean foundAny = false;
T result = null;
for (T element : this stream) {
    if (!foundAny) {
        foundAny = true;
        result = element;
    }
    else
        result = accumulator.apply(result, element);
}
return foundAny ? Optional.of(result) : Optional.empty();
  • 如果用一个参数的重载方法去求最小值代码如下:
java 复制代码
// 使用reduce求所有作者中年龄的最小值
List<Author> authors = getAuthors();
Optional<Integer> minOptional = authors.stream()
    .map(author -> author.getAge())
    .reduce((result, element) -> result > element ? element : result);
minOptional.ifPresent(age-> System.out.println(age));

4. 注意事项

  • 惰性求值(如果没有终结操作,没有中间操作是不会得到执行的)
  • 流是一次性的(一旦一个流对象经过一个终结操作后。这个流就不能再被使用)
  • 不会影响原数据(我们在流中可以多数据做很多处理。但是正常情况下是不会影响原来集合中的元素的。这往往也是我们期望的)
相关推荐
周末程序猿3 分钟前
Linux高性能网络编程十谈|C++11实现22种高并发模型
后端·面试
ZHOU_WUYI10 分钟前
Flask与Celery 项目应用(shared_task使用)
后端·python·flask
冒泡的肥皂1 小时前
强大的ANTLR4语法解析器入门demo
后端·搜索引擎·编程语言
IT_陈寒1 小时前
Element Plus 2.10.0 重磅发布!新增Splitter组件
前端·人工智能·后端
有梦想的攻城狮2 小时前
spring中的@RabbitListener注解详解
java·后端·spring·rabbitlistener
Java水解2 小时前
MySQL DQL全面解析:从入门到精通
后端·mysql
Aurora_NeAr2 小时前
Apache Spark详解
大数据·后端·spark
程序员岳焱2 小时前
Java 程序员成长记(二):菜鸟入职之 MyBatis XML「陷阱」
java·后端·程序员
hello早上好2 小时前
BeanFactory 实现
后端·spring·架构
我命由我123452 小时前
Spring Boot 项目集成 Redis 问题:RedisTemplate 多余空格问题
java·开发语言·spring boot·redis·后端·java-ee·intellij-idea