栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

stream基础知识

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

stream基础知识

stream简介

Java8中的Stream是对集合(Collection)对象功能的增强,它专注于对集合对象进行各种非常便利、高效的聚合操作,或者大批量数据操作等操作;Stream不是集合元素,它不是数据结构并不保存数据,它是有关算法和计算的。

stream的创建
public static void main(String[] args) {
        //通过Collection系列集合通过的stream()或parallelStream()方法生成流
        List list = new ArrayList<>();
        list.add("a");
        list.add("b");
        //创建串行流
        Stream collectionStream = list.stream();
        //创建并行流
        Stream collectionParallelStream = list.parallelStream();

        //通过Arrays中的静态方法stream()获取数组流
        Integer[] arrays = new Integer[]{1,2,3};
        Stream arraysStream = Arrays.stream(arrays);

        //通过Stream类中的静态方法of()获取流
        Stream stream = Stream.of(1, "a");

        //无限流(可以无限生成数据的流)
        

        Stream iterateStream = Stream.iterate(0, (e) -> e + 2);

        //生成
        Stream generateStream = Stream.generate(() -> Math.random());
 
Stream的操作 

Stream的操作有中间操作和终止操作2中类型操作;

中间操作只会处理数据,不会生成结果;
终止操作是终止中间操作并且生成中间操作后的数据。

Stream的中间操作

准备数据

public class User {
    private String name;
    private Integer age;
    private Double money;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    public User(String name, Integer age, Double money) {
        this.name = name;
        this.age = age;
        this.money = money;
    }

    public User() {
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + ''' +
                ", age=" + age +
                ", money=" + money +
                '}';
    }

    
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof User)) return false;
        User user = (User) o;
        return Objects.equals(getName(), user.getName()) &&
                Objects.equals(getAge(), user.getAge());
    }

    @Override
    public int hashCode() {
        return Objects.hash(getName(), getAge());
    }
}

	static List userList = new ArrayList<>();
    static {

        userList.add(new User("张三",20,1000D));
        userList.add(new User("李四",21,2000D));
        userList.add(new User("王五",22,3000D));
        userList.add(new User("赵六",23,4000D));
        userList.add(new User("张三",20,2000D));

    }

filter(筛选操作)

public static void main(String[] args) {
        

        Stream userStream = userList.stream().filter(e -> e.getAge() > 22);
        //输出筛选后的数据
        userStream.forEach(System.out::println);
        
    }

limit(截断流,使其元素不超过给定数量)

public static void main(String[] args) {

        
        Stream userStream = userList.stream().limit(3);
        //输出筛选后的数据
        userStream.forEach(System.out::println);

    }

skip

public static void main(String[] args) {

        
        Stream userStream = userList.stream().skip(2);
        //输出筛选后的数据
        userStream.forEach(System.out::println);

    }

limit和skip组合成分页功能

public static void main(String[] args) {

        
        Integer page = 0;
        Integer rows = 2;
        Integer start = page * rows;
        if(start > userList.size()){
            start = userList.size() - rows;
        }
        Stream userStream = userList.stream().skip(start).limit(rows);
        //输出筛选后的数据
        userStream.forEach(System.out::println);
    }

filter与limit和skip组合的区别

public static void main(String[] args) {


        
        Stream limitUserStream = userList.stream().filter(e -> {
            System.out.println("1111");
            return e.getAge() > 19;
        }).limit(1);
        //输出筛选后的数据
        limitUserStream.forEach(System.out::println);

        
        Stream skipUserStream = userList.stream().filter(e -> {
            System.out.println("2222");
            return e.getAge() > 19;
        }).skip(1);
        //输出筛选后的数据
        skipUserStream.forEach(System.out::println);

    }

distinct(去重)

public static void main(String[] args) {

        
        //类对象集合
        Stream userStream = userList.stream().distinct();
        //输出筛选后的数据
        userStream.forEach(System.out::println);
        //基本数据集合
        List integerList = new ArrayList<>();
        integerList.add(1);
        integerList.add(1);
        Stream distinctInteger = integerList.stream().distinct();
        distinctInteger.forEach(System.out::println);
        //基本数据集合
        List stringList = new ArrayList<>();
        stringList.add("a");
        stringList.add("a");
        Stream distinctString = stringList.stream().distinct();
        distinctString.forEach(System.out::println);

    }

map(映射)

public static void main(String[] args) {

        
        //获取用户姓名
        Stream userNameStream = userList.stream().map(e -> e.getName());
        //输出筛选后的数据
        userNameStream.forEach(System.out::println);
    }

flatMap(拍平映射)

public static void main(String[] args) {

        
        //获取用户姓名中的子的集合
        Stream userNameStream = userList.stream().map(User::getName).flatMap(e ->{
            List list = new ArrayList<>();
            for (Character ch : e.toCharArray()){
                list.add(ch);
            }
            return list.stream();
        });
        userNameStream.forEach(System.out::println);
    }

sorted(排序)

public static void main(String[] args) {
public static void main(String[] args) {
        
        Stream sortedUser = userList.stream().sorted((first, second) -> {
            Integer firstAge = first.getAge();
            Integer secondAge = second.getAge();
            int i = firstAge - secondAge;
            if (i == 0) {

                String firstName = first.getName();
                String secondName = second.getName();
                i = firstName.hashCode() - secondName.hashCode();
            }
            return i;
        });
        
        sortedUser.forEach(System.out::println);
    }
终止操作

allMatch、anyMatch和noneMatch匹配

public static void main(String[] args) {
        
        boolean allMatchFlag = userList.stream().allMatch(e -> e.getAge() == 20);
        System.out.println("allMatchFlag:"+allMatchFlag);

        
        boolean anyMatchFlag = userList.stream().anyMatch(e -> e.getAge() == 20);
        System.out.println("anyMatchFlag:"+anyMatchFlag);


        
        boolean noneMatchFlag = userList.stream().noneMatch(e -> e.getAge() == 200);
        System.out.println("noneMatchFlag:"+noneMatchFlag);

    }

findFirst和findAny查找

 public static void main(String[] args) {
        
        Optional opFirst = userList.stream().findFirst();

        if(opFirst.isPresent()){
            User user = opFirst.get();
            System.out.println(user);
        }

        
        for (int i = 0; i < 100; i++){
            Optional opAnyFirst = userList.stream().findAny();

            if(opAnyFirst.isPresent()){
                User user = opAnyFirst.get();
                System.out.println(user);
            }
        }

        for (int i = 0; i < 100; i++){
            Optional opAnySecond = userList.parallelStream().findAny();

            if(opAnySecond.isPresent()){
                User user = opAnySecond.get();
                System.out.println(user);
            }
        }
    }

count、max和min

public static void main(String[] args) {


        //获取流中是总个数
        long count = userList.stream().count();
        System.out.println("count:"+count);
        //获取流中年龄最大的用户
        Optional maxOP = userList.stream().max((first, second) -> Double.compare(first.getAge(), second.getAge()));
        if(maxOP.isPresent()){
            User user = maxOP.get();
            System.out.println(user);
        }

        //获取流中年龄最小的年龄值
        Optional minOP = userList.stream().map(e -> e.getAge()).min(Double::compare);
        if(maxOP.isPresent()){
            Integer minAge = minOP.get();
            System.out.println(minAge);
        }

    }

reduce

public static void main(String[] args) {
        
        
        Double reduce = userList.stream().map(e -> e.getMoney()).reduce(0d, (x, y) -> x + y);
        System.out.println(reduce);
        
        Optional reduceOp = userList.stream().map(e -> e.getMoney()).reduce(Double::sum);
        if(reduceOp.isPresent()){
            System.out.println(reduceOp.get());
        }
    }

collect(收集)

public static void main(String[] args) {
        
        String str = userList.stream().map(e -> e.getName()).collect(Collectors.joining(","));
        System.out.println(str);

        
        Set set = userList.stream().map(e -> e.getName()).collect(Collectors.toSet());
        System.out.println(set);
        
        Set hashSet = userList.stream().map(e -> e.getName()).collect(Collectors.toCollection(HashSet::new));
        System.out.println(hashSet);

        
        Map map = userList.stream().collect(Collectors.toMap(e -> e.getName(), e -> e.getMoney(),(oldVal, currVal) -> currVal));
        System.out.println(map);

    }

计算

public static void main(String[] args) {
        
        Long count = userList.stream().collect(Collectors.counting());
        System.out.println("count:"+count);

        
        Double sum = userList.stream().collect(Collectors.summingDouble(e -> e.getMoney()));
        System.out.println("sum:"+sum);

        
        Double average = userList.stream().collect(Collectors.averagingDouble(e -> e.getMoney()));
        System.out.println("average:"+average);

        
        Optional maxOp = userList.stream().collect(Collectors.maxBy((first, second) -> Double.compare(first.getMoney(), second.getMoney())));
        if(maxOp.isPresent()){
            System.out.println("maxUser:"+maxOp.get());
        }

        
        Optional minOp = userList.stream().map(e -> e.getMoney()).collect(Collectors.minBy(Double::compare));
        if(minOp.isPresent()){
            System.out.println("min"+minOp.get());
        }


        System.out.println("----------------------");
        
        DoubleSummaryStatistics dss = userList.stream().collect(Collectors.summarizingDouble(User::getMoney));
        System.out.println("max:"+dss.getMax());
        System.out.println("count:"+dss.getCount());
        System.out.println("min:"+dss.getMin());
        System.out.println("average:"+dss.getAverage());
        System.out.println("sum:"+dss.getSum());

    }

分组

public static void main(String[] args) {

        
        Map> groupCollect = userList.stream().collect(Collectors.groupingBy(User::getAge));
        System.out.println(groupCollect);

        
        Map>> zdyGroupCollect = userList.stream().collect(Collectors.groupingBy(User::getName, Collectors.groupingBy(e -> {
            if (e.getAge() <= 10) {
                return "儿童";
            } else if (e.getAge() <= 18) {
                return "青年";
            } else {
                return "非青年";
            }
        })));
        System.out.println(zdyGroupCollect);
        
        Map>> moreGroupCollect = userList.stream().collect(Collectors.groupingBy(User::getName, Collectors.groupingBy(User::getAge)));
        System.out.println(moreGroupCollect);

    }

分区

public static void main(String[] args) {
        Map> collect = userList.stream().collect(Collectors.partitioningBy(e -> e.getMoney() > 2000));
        System.out.println(collect);
    }

串行流与并行流

public static void main(String[] args) {

        
        //串行流
        Instant sequentialStart = Instant.now();
        long sequentialResult = LongStream.rangeClosed(0, 100000000000l).sequential().reduce(0, Long::sum);//
        Instant sequentialEnd = Instant.now();
        System.out.println("串行流耗时:"+Duration.between(sequentialStart, sequentialEnd).toMillis());
        System.out.println(sequentialResult);

        //并行流
        Instant parallelStart = Instant.now();
        long parallelResult = LongStream.rangeClosed(0, 100000000000l).parallel().reduce(0, Long::sum);//4891
        Instant parallelEnd = Instant.now();
        System.out.println("并行流耗时:"+Duration.between(parallelStart, parallelEnd).toMillis());
        System.out.println(parallelResult);
    }
转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号