Stream流学习记录

1. 创建流

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

        List<Author> authors =new ArrayList<>();
		Stream<Author> stream = authors.stream();

数组:Arrays.stream(数组)或者使用Stream.of来创建

        Integer[] arr = {1,2,3,4,5};
        Stream<Integer> stream = Arrays.stream(arr);
        Stream<Integer> stream2 = Stream.of(arr);

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

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

        Stream<Map.Entry<String, Integer>> stream = map.entrySet().stream();


2. 中间操作

filter

对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中。

// 打印所有姓名长度大于1的作家的姓名
List<Author> authors = new ArrayList<>();
        authors.stream()
                .filter(author -> author.getName().length()>1)
                .forEach(author -> System.out.println(author.getName()));

map

对流中的元素进行计算或转换。

// 打印所有作家的姓名
List<Author> authors = new ArrayList<>();
        authors.stream()
                .map(author -> author.getName()) // 此时流中数据是String name
                .forEach(name->System.out.println(name));
        

// 所有年龄+10并打印
        authors.stream()
                .map(author -> author.getAge()) // 此时流中数据是Integer age
                .map(age->age+10)
                .forEach(age-> System.out.println(age));

distinct

去除流中的重复元素。

// 打印所有作家的姓名,并且要求其中不能有重复元素。
List<Author> authors = new ArrayList<>();
        authors.stream()
                .distinct()
                .forEach(author -> System.out.println(author.getName()));

注意:distinct方法是依赖Object的equals方法来判断是否是相同对象的。所以需要注意重写equals方法。


sorted

对流中的元素进行排序。

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

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


limit

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

 // 对流中的元素按照年龄进行降序排序,并且不能有重复的元素,然后打印其中年龄最大的两个作家的姓名。   
 List<Author> authors = new ArrayList<>();
        authors.stream()
                .distinct()
                .sorted()
                .limit(2)
                .forEach(author -> System.out.println(author.getName()));

skip

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

// 打印除了年龄最大的作家外的其他作家,要求不能有重复元素,并且按照年龄降序排序。
// 等于去掉第一个数据
        List<Author> authors = new ArrayList<>();
        authors.stream()
                .distinct()
                .sorted()
                .skip(1)
                .forEach(author -> System.out.println(author.getName()));

举一反三

用limit和skip实现分页功能:

page:当前页,page应当大于等于1

pageSize:每页几条数据

// 如要分页:第二页 每页显示5条 = 从第6条数据开始取5条
List<Author> authors = new ArrayList<>();
        authors.stream()
                .skip((page - 1) * pageSize) // 跳过前5条数据
                .limit(pageSize) // 截取5条数据
                .collect(Collectors.toList());

 flatMap

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

 如果Author类中的book也是一个对象,并且一个author对应多本book的话,要对book操作需要把book也转换成一个新的流

//   打印所有书籍的名字。要求对重复的元素进行去重。
List<Author> authors = new ArrayList<>();
        authors.stream()
                .flatMap(author -> author.getBooks().stream()) // 此时流为Stream<Book>
                .distinct()
                .forEach(book -> System.out.println(book.getName()));
// 打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式:哲学,爱情  爱情
        List<Author> authors = new ArrayList<>();
        authors.stream()
                .flatMap(author -> author.getBooks().stream()) // Stream<Book>
                .distinct() // 对book进行去重
                .flatMap(book -> Arrays.stream(book.getCategory().split(","))) // 获取book的分类并按","分割成数组,再转换成一个新的流,Stream<String>
                .distinct()
                .forEach(category-> System.out.println(category));


3. 终结操作

forEach

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

// 输出所有作家的名字
List<Author> authors = new ArrayList<>();
        authors.stream()
                .map(author -> author.getName())
                .distinct()
                .forEach(name-> System.out.println(name));

count

获取当前流中元素的个数。

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

 max&min

可以用来获得流中的最值。

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

        List<Author> authors = new ArrayList<>();
        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());

collect

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

List<Author> authors = new ArrayList<>();
// 获取一个存放所有作者名字的List集合。
        List<String> nameList = authors.stream()
                .map(author -> author.getName())
                .collect(Collectors.toList());
        System.out.println(nameList);


// 获取一个所有书名的Set集合。
        Set<Book> books = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .collect(Collectors.toSet());
        System.out.println(books);


// 获取一个Map集合,map的key为作者名,value为List<Book>
        Map<String, List<Book>> map = authors.stream()
                .distinct()
                .collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));
        System.out.println(map);

anyMatch

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

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

allMatch

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

// 判断是否所有的作家都是成年人
        List<Author> authors = new ArrayList<>();
        boolean flag = authors.stream()
                .allMatch(author -> author.getAge() >= 18);
        System.out.println(flag);

noneMatch

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

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

findAny

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

// 获取任意一个年龄大于18的作家,如果存在就输出他的名字
        List<Author> authors = new ArrayList<>();
        Optional<Author> optionalAuthor = authors.stream()
                .filter(author -> author.getAge() > 18)
                .findAny();
        optionalAuthor.ifPresent(author -> System.out.println(author.getName()));

findFirst

获取流中的第一个元素。

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

reduce归并

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

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

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

T result = identity;
for (T element : this stream)
    result = accumulator.apply(result, element)
return result;

其中identity就是我们可以通过方法参数传入的初始值,accumulator的apply具体进行什么计算也是我们通过方法参数来确定的。

// 使用reduce求所有作者年龄的和
        List<Author> authors = new ArrayList<>();
        Integer sum = authors.stream()
                .distinct()
                .map(author -> author.getAge())
                .reduce(0, (result, element) -> result + element);
        System.out.println(sum);

.reduce(0, (result, element) -> result + element);

0:传入的初始值,也就是result的初始值

result:计算的初始值,也是计算的结果

element:流中数据的值

        List<Author> authors = new ArrayList<>();
// 使用reduce求所有作者中年龄的最大值
        Integer max = authors.stream()
                .map(author -> author.getAge())
                .reduce(Integer.MIN_VALUE, (result, element) -> result < element ? element : result);
        System.out.println(max);


// 使用reduce求所有作者中年龄的最小值
        Integer min = authors.stream()
                .map(author -> author.getAge())
                .reduce(Integer.MAX_VALUE, (result, element) -> result > element ? element : result);
        System.out.println(min);

reduce一个参数的重载形式内部的计算

      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();

这时result会把流中的第一个值当成初始值

如果用一个参数的重载方法去求最小值代码如下:

        // 使用reduce求所有作者中年龄的最小值
        List<Author> authors = new ArrayList<>();
        Optional<Integer> minOptional = authors.stream()
                .map(author -> author.getAge())
                .reduce((result, element) -> result > element ? element : result);
        minOptional.ifPresent(age-> System.out.println(age));

 

注意事项

  • 惰性求值(如果没有终结操作,没有中间操作是不会得到执行的)

  • 流是一次性的(一旦一个流对象经过一个终结操作后。这个流就不能再被使用)

  • 不会影响原数据(我们在流中可以多数据做很多处理。但是正常情况下是不会影响原来集合中的元素的。这往往也是我们期望的)

学习资料来自b站up主三更草堂,感谢大佬的学习视频:

不会函数式编程?你确定能看懂公司代码?-java8函数式编程(Lambda表达式,Optional,Stream流)从入门到精通-最通俗易懂的函数式编程教学

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用Stream遍历Map集合,可以通过调用Map接口的entrySet()方法获取一个Set集合,然后使用Stream的forEach()方法来遍历这个Set集合。在forEach()方法中,可以使用Lambda表达式来对每个Entry进行操作。以下是一个示例代码: ``` Map<String, Integer> map = new HashMap<>(); map.put("a", 1); map.put("b", 2); map.put("c", 3); map.entrySet().stream().forEach(entry -> { String key = entry.getKey(); Integer value = entry.getValue(); System.out.println("Key: " + key + ", Value: " + value); }); ``` 在这个示例中,我们首先创建了一个包含键值对的Map集合。然后,通过调用entrySet()方法获取一个Set集合,再通过stream()方法将这个Set集合转换为一个Stream。接下来,使用forEach()方法来遍历这个Stream,对每个Entry进行操作。在Lambda表达式中,我们可以通过entry.getKey()和entry.getValue()方法分别获取键和值,并将它们打印出来。 这样,就可以使用Stream遍历Map集合了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Stream的方式遍历map,筛选数据](https://blog.csdn.net/qq_44716086/article/details/126332094)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Java学习与复习笔记--Stream思想概述:](https://blog.csdn.net/gkx826/article/details/108543430)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [怎么在java 8的map中使用stream](https://download.csdn.net/download/weixin_38719719/14853217)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值