当前位置:   article > 正文

Java 8 Stream API的使用

Java 8 Stream API的使用

前言

Stream(流)是一个来自数据源的元素队列,它可以支持聚合操作。

● 数据源:流的数据来源,构造Stream对象的数据源,比如通过一个List来构造Stream对象,这个List就是数据源;
● 聚合操作:对Stream对象进行处理后使得Stream对象返回指定规则数据的操作称之为聚合操作,比如filter、map、limit、sorted等都是聚合操作。

Stream 聚合操作

准备一个Person类

class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return name;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

然后根据这个对象,我们构造一些数据

 List<Person> persons =
                Arrays.asList(
                        new Person("Max", 18),
                        new Person("Peter", 23),
                        new Person("Pamela", 23),
                        new Person("David", 12));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

filter 操作

对Stream中的元素进行过滤操作,当设置条件返回true时返回相应元素。

  List<Person> filtered=persons.stream()//创建流
                .filter(p->p.name.startsWith("P"))//过滤出名字以p开头的
                .collect(Collectors.toList());//生成一个新的List
        System.out.println(filtered);
  • 1
  • 2
  • 3
  • 4

map 操作

对Stream中的元素进行转换处理后获取,比如可以将Person对象转换成Long对象。我们经常会有这样的需求:需要把某些对象的id提取出来,然后根据这些id去查询其他对象,这时可以使用此方法。

@Test
public void mapTest(){
    //map操作:获取所有对象的名字
    List<Long> idList = menuList.stream()
    .map(menu -> person.getAge())
    .collect(Collectors.toList());
    LOGGER.info("map操作:{}",idList);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

limit

从Stream中获取指定数量的元素。

 List<Person> firstFiveList = menuList.stream()
            .limit(5)
            .collect(Collectors.toList());
    LOGGER.info("limit操作:{}",firstFiveList);
  • 1
  • 2
  • 3
  • 4

Count

仅获取Stream中元素的个数。

@Test
    //count操作:获取所有一级菜单的个数
    long count = menuList.stream()
    .filter(p -> p.age == 18)
    .count();
    LOGGER.info("count操作:{}",count);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

sorted

对Stream中元素按指定规则进行排序。

//sorted操作:将所有名字按照sort字段进行排序
    List<Person> sortedList = menuList.stream()
            .sorted((p1,p2)->{return p1.getAge().compareTo(p2.getAge());})
            .collect(Collectors.toList());
    LOGGER.info("sorted操作:{}",sortedList);
  • 1
  • 2
  • 3
  • 4
  • 5

Skip

跳过指定个数的Stream中元素,获取后面的元素。

   //skip操作:跳过前5个元素,返回后面的
    List<Person> skipList = menuList.stream()
            .skip(5)
            .collect(Collectors.toList());
    LOGGER.info("skip操作:{}",skipList);
  • 1
  • 2
  • 3
  • 4
  • 5

转换方法

这个转换 Map 的思路是将 persons 集合中的每个对象根据年龄分组,如果有不同的人具有相同的年龄,则将这些人的名字用分号连接起来作为一个年龄对应的多个名字的字符串。

 //转换Map集合
        Map<Integer,String> map=persons
                .stream()
                .collect(Collectors.toMap(
                        p->p.age,
                        p->p.name,
                        (name1,name2) -> name1+";"+name2
                ));
        System.out.println(map);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/478774
推荐阅读
相关标签
  

闽ICP备14008679号