stream流的基本使用

public class StreamTest {

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(7, 6, 9, 3, 8, 2, 1);

        //遍历筛选出符合条件的元素
        list.stream().filter(x -> x > 6).forEach(System.out::println);
        //匹配第一个
        Optional<Integer> findFirst = list.stream().findFirst();
        //匹配任意一个元素
        Optional<Integer> any = list.stream().findAny();
        //是否包含符合特定条件的元素
        boolean anyMatch = list.stream().anyMatch(x -> x > 6);
        //所有的元素是否都符合条件
        boolean allMatch = list.stream().allMatch(x -> x > 6);
        ArrayList<Person> personList = new ArrayList<>();
        personList.add(new Person("Tom", 8900, 23, "male", "New York"));
        personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
        personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
        personList.add(new Person("Anni", 8200, 24, "female", "New York"));
        personList.add(new Person("Owen", 9500, 25, "male", "New York"));
        personList.add(new Person("Alisa", 7900, 26, "female", "New York"));
        //筛选出salary大于8000的姓名
        List<String> filterList = personList.stream().filter(x -> x.getSalary() > 8000).map(Person::getName).collect(Collectors.toList());
        List<String> list2 = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd");
        //获取String集合中最长的元素
        Optional<String> max = list2.stream().max(Comparator.comparing(String::length));
        //System.out.println(max.get());
        //自然排序,获取集合中最大的值
        Optional<Integer> max1 = list.stream().max(Integer::compareTo);
        //自定义排序,获取集合最大的值
        Optional<Integer> max2 = list.stream().max(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }
        });
        //获取员工salary最高的
        Optional<Person> maxSalary = personList.stream().max(Comparator.comparing(Person::getSalary));
        //System.out.println(maxSalary.get().getSalary());
        //统计集合大于6的元素个数
        long count = list.stream().filter(x -> x > 6).count();
        //-----映射(map/flatMap)
        //将英文字符串数组的元素全部改为大写
        String[] strArr = { "abcd", "bcdd", "defde", "fTr" };
        List<String> stringList = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList());
        //将整数数组每个元素+3
        List<Integer> integerList = list.stream().map(x -> x + 3).collect(Collectors.toList());
        //将每个员工的salary增加1000
        List<Person> personList1 = personList.stream().map(person -> {
            person.setSalary(person.getSalary() + 1000);
            return person;
        }).collect(Collectors.toList());
        //System.out.println(personList1.get(0).getName()+"-->"+personList1.get(0).getSalary());
        //将两个字符串数组组合并合成一个新的字符串数组
        List<String> list3 = Arrays.asList("m,k,l,a", "1,3,5,7");
        List<String> newList3 = list3.stream().flatMap(s -> {
            String[] split = s.split(",");
            Stream<String> s2 = Arrays.stream(split);
            return s2;
        }).collect(Collectors.toList());
        //System.out.println(newList3);
        //-------归约(reduce):归约,也称缩减,顾名思义,是把一个流缩减成一个值,能实现对集合求和、求乘积和求最值操作。
        //集合元素之和三种方式
        Optional<Integer> reduce = list.stream().reduce((x, y) -> x + y);
        Optional<Integer> reduce1 = list.stream().reduce(Integer::sum);
        Integer reduce2 = list.stream().reduce(0, Integer::sum);
        //集合元素的乘积
        Optional<Integer> reduce3 = list.stream().reduce((x, y) -> x * y);
        //求最大值方式1
        Optional<Integer> reduce4 = list.stream().reduce((x, y) -> x > y ? x : y);
        //求最大值方式1
        Integer reduce5 = list.stream().reduce(1, Integer::max);
        //求员工salary之和
        Optional<Integer> reduce6 = personList.stream().map(Person::getSalary).reduce(Integer::sum);
        //求员工最高工资
        Integer reduce7 = personList.stream().reduce(0, (maxSal, p) -> maxSal > p.getSalary() ? maxSal : p.getSalary(), Integer::max);
        //归集
        List<Integer> list4 = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20);
        List<Integer> collectList = list4.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());
        Set set = list4.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet());
        Map<String, Person> personMap = personList.stream().filter(p -> p.getSalary() > 8000).collect(Collectors.toMap(Person::getName, p -> p));
        System.out.println(personMap);
    }
}

class Person {
    private String name;  // 姓名
    private int salary; // 薪资
    private int age; // 年龄
    private String sex; //性别
    private String area;  // 地区

    // 构造方法
    public Person(String name, int salary, int age,String sex,String area) {
        this.name = name;
        this.salary = salary;
        this.age = age;
        this.sex = sex;
        this.area = area;
    }

    public String getName() {
        return name;
    }

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

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    public int getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }
}
public class StreamTest02 {

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20);
        List<Integer> listNew = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());
        Set<Integer> set = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet());

        List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Tom", 8900, 23, "male", "New York"));
        personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
        personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
        personList.add(new Person("Anni", 8200, 24, "female", "New York"));
        //归集
        Map<String, Person> personMap = personList.stream().filter(p -> p.getSalary() > 8000)
                .collect(Collectors.toMap(Person::getName, p -> p));
        //统计员工总数
        Long count = personList.stream().collect(Collectors.counting());
        //求平均工资
        Double average = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));
        //求最高工资
        Optional<Integer> maxSalary = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compareTo));
        //一次性统计所有信息
        DoubleSummaryStatistics summaryStatistics = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));
        //分组(partitioningBy/groupingBy)
        //按工资是否高于8000进行分组
        Map<Boolean, List<Person>> part = personList.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));
        Map<Boolean, List<Person>> group = personList.stream().collect(Collectors.groupingBy(p -> p.getSalary()>8000));
        //按性别进行分组
        Map<String, List<Person>> groupSex = personList.stream().collect(Collectors.groupingBy(Person::getSex));
        //先按性别再按地区进行分组
        Map<String, Map<String, List<Person>>> sexAndArea = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));
        //结合(Joining)
        //获取所有员工的姓名用,进行结合
        String names = personList.stream().map(Person::getName).collect(Collectors.joining(","));
        //排序(sorted)
        //按工资由高到低排序(自然排序)
        List<String> sorted = personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName).collect(Collectors.toList());
        //按工资降序排序(自然排序)
        List<String> descSorted = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed()).map(Person::getName).collect(Collectors.toList());
        //先按工资再按年龄
        List<String> salaryAndAge = personList.stream().sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName).collect(Collectors.toList());
        //自定义排序
        List<String> collect = personList.stream().sorted((p1, p2) -> {
            if (p1.getSalary() == p2.getSalary()) {
                return p2.getAge() - p1.getAge();
            } else {
                return p1.getSalary() - p2.getSalary();
            }
        }).map(Person::getName).collect(Collectors.toList());
        //提取/组合   流也可以进行合并、去重、限制、跳过等操作。
        String[] arr1 = { "a", "b", "c", "d" };
        String[] arr2 = { "d", "e", "f", "g" };
        //合并并且去重
        Stream<String> stream1 = Stream.of(arr1);
        Stream<String> stream2 = Stream.of(arr2);
        List<String> stringList = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());
        //获取前n个数据
        List<Integer> integerList = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());
        //跳过前n个数据
        List<Integer> skipList = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList());
        System.out.println(skipList);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值