Stream流

1 find/filter/match

        List<Integer> list = Arrays.asList(13, 5, 9, 3, 4, 4, 11);
        Optional<Integer> first = list.stream().filter(x -> x > 6).findFirst();
        Optional<Integer> any = list.stream().filter(x -> x > 7).findAny();
        boolean b = list.stream().anyMatch(x -> x < 0);
        list.stream().forEach(e -> {
            System.out.println("foreach: "+e+ "* 2 = "+e*2);
        });
        System.out.println("匹配第一个:"+first.get());
        System.out.println("匹配任意一个:"+any.get());
        System.out.println("是否存在小于0的值:"+b);

在这里插入图片描述

2 list 排序

       List<Student> studentList = new ArrayList<Student>();
        studentList.add(new Student("张三",16,"男",60,66,90));
        studentList.add(new Student("李四",18,"男",50,46,20));
        studentList.add(new Student("王五",18,"男",97,96,91));
        studentList.add(new Student("小刘",18,"男",80,66,91));
        studentList.add(new Student("小丽",17,"女",65,66,79));
        studentList.add(new Student("菲菲",21,"女",65,66,79));
        studentList.add(new Student("小明",20,"男",22,66,14));

        studentList.sort(((o1, o2) -> {
            return o1.getName().compareTo(o2.getName());
        }));
        System.out.println("比较名字:"+studentList);

        System.out.println("===========================");
        studentList.sort(((o1, o2) -> {
             return o1.getYingyu() - o2.getYingyu();
        }));
        System.out.println("根据语文成绩升序排序:"+studentList);

        System.out.println("===========================");
        studentList.sort(Comparator.comparing(Student::getYuwen).reversed());
        System.out.println("根据语文成绩降序排序:"+studentList);


        System.out.println("===========================");
        studentList.sort(Comparator.comparing(Student::getAge).reversed().thenComparing(Student::getYuwen));
        System.out.println("先根据年龄降序排序,再根据语文成绩升序排序:"+studentList);

        System.out.println("===========================");
        Collections.sort(studentList, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o2.getYingyu()-o1.getYingyu();
            }
        });
        System.out.println("根据英语成绩降序排序:"+studentList);

        System.out.println("===========================");
        Collections.sort(studentList, (Student o1,Student o2) -> o1.getAge() - o2.getAge());
        System.out.println("根据年龄升序排序:"+studentList);
        
        System.out.println("===========================");
        studentList.sort(((o1, o2) -> {
            if (o1.getAge()-o2.getAge() > 0){
                return 1;
            }
            else if (o1.getAge()-o2.getAge() < 0){
                return -1;
            }
            //多条件时 此处不能返回0

            if (o2.getShuxue() - o1.getShuxue() > 0){
                return 1;
            }
            else if (o2.getShuxue() - o1.getShuxue() < 0){
                return -1;
            }
            else {
                return 0;
            }
        }));
        System.out.println("多条件 先根据年龄升序,再根据数学成绩降序:"+studentList);

在这里插入图片描述

3.List操作

        List<Student> studentList = new ArrayList<Student>();
        studentList.add(new Student("张三",16,"男",60,66,90));
        studentList.add(new Student("李四",18,"男",50,46,20));
        studentList.add(new Student("王五",18,"男",97,96,91));
        studentList.add(new Student("小刘",18,"男",80,66,91));
        studentList.add(new Student("小丽",17,"女",65,66,79));
        studentList.add(new Student("菲菲",21,"女",65,66,79));
        studentList.add(new Student("小明",20,"男",22,66,14));

        //map
        List<String> students1 = studentList.stream().map(Student::getName).collect(Collectors.toList());
        System.out.println("收集班级学生姓名:"+students1);
        System.out.println("===========================");

        List<Student> students2 = studentList.stream().map(student -> {
            if (student.getYingyu() < 60) {
                student.setYingyu(student.getYingyu() + 10);
            }
            return student;
        }).collect(Collectors.toList());
        System.out.println("给班级里面英语成绩小于60的学生加上10分:"+students2);
        System.out.println("===========================");

        Map<String, Integer> collect = studentList.stream().collect(Collectors.toMap(Student::getName, Student::getAge));
        System.out.println("收集班级学生和年龄到map:"+ collect);
        System.out.println("===========================");

        long count = studentList.stream().count();
        System.out.println("计算学生人数:"+count);
        System.out.println("===========================");

        Integer maxAge = studentList.stream().map(Student::getAge).collect(Collectors.maxBy(Integer::compareTo)).get();
        System.out.println("年龄最大为:"+maxAge);
        System.out.println("===========================");

        Integer minAge = studentList.stream().map(Student::getAge).collect(Collectors.minBy(Integer::compareTo)).get();
        System.out.println("年龄最小为:"+minAge);
        System.out.println("===========================");

        Integer sumAge = studentList.stream().collect(Collectors.summingInt(Student::getAge));
        System.out.println("年龄总和为:"+sumAge);
        System.out.println("===========================");

        Double avgAge = studentList.stream().collect(Collectors.averagingDouble(Student::getAge));
        System.out.println("平均年龄为:"+avgAge);
        System.out.println("===========================");

        Map<Integer, List<Student>> groupByAge = studentList.stream().collect(Collectors.groupingBy(Student::getAge));
        System.out.println("根据年龄进行分组:"+groupByAge);
        System.out.println("===========================");

        Map<Boolean, List<Student>> age = studentList.stream().collect(Collectors.partitioningBy(e -> e.getAge() >= 18));
        System.out.println("根据年龄分成两个区:"+age);
        System.out.println("===========================");

        Integer integer = studentList.stream().map(Student::getAge).collect(Collectors.reducing(Integer::sum)).get();
        System.out.println("规约 收集年龄总和:"+integer);
        System.out.println("===========================");


ListMap:第三个参数指定当出现重复的key时,使用哪一个value

Map<String, String> collect = wearableJobDictionaryRepository.findAll().stream().
collect(Collectors.toMap(WearableJobDictionary::getDictKey,WearableJobDictionary::getDictVal, 
(dictVal1, dictVal2) -> dictVal2));

4.filter max min count

public class StreamTest {
	public static void main(String[] args) {
		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"));
		personList.add(new Person("Owen", 9500, 25, "male", "New York"));
		personList.add(new Person("Alisa", 7900, 26, "female", "New York"));

		List<String> fiterList = personList.stream().filter(x -> x.getSalary() > 8000).map(Person::getName)
				.collect(Collectors.toList());
		System.out.print("薪资高于8000美元的员工:" + fiterList);
	}
}

薪资高于8000美元的员工:[Tom, Anni, Owen]

List<String> list = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd");
Optional<String> max = list.stream().max(Comparator.comparing(String::length));
System.out.println("最长的字符串:" + max.get());

最长的字符串:weoujgsd
List<Integer> list = Arrays.asList(7, 6, 4, 8, 2, 11, 9);

		long count = list.stream().filter(x -> x > 6).count();
		System.out.println("list中大于6的元素个数:" + count);

list中大于6的元素个数:4

5.map flatMap

String[] strArr = { "abcd", "bcdd", "defde", "fTr" };
		List<String> strList = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList());

		List<Integer> intList = Arrays.asList(1, 3, 5, 7, 9, 11);
		List<Integer> intListNew = intList.stream().map(x -> x + 3).collect(Collectors.toList());

		System.out.println("每个元素大写:" + strList);
		System.out.println("每个元素+3:" + intListNew);

每个元素大写:[ABCD, BCDD, DEFDE, FTR]
每个元素+3[4, 6, 8, 10, 12, 14]
// 输出字符串集合中每个字符串的长度
    List<String> stringList = Arrays.asList("mu", "优快云", "hello",
            "world", "quickly");
    stringList.stream().mapToInt(String::length).forEach(System.out::println);
    // 将int集合的每个元素增加1000
    List<Integer> integerList = Arrays.asList(4, 5, 2, 1, 6, 3);
    integerList.stream().mapToInt(x -> x + 1000).forEach(System.out::println);

    List<Double> doubleList = Arrays.asList(1.0, 2.0, 3.0, 4.0, 2.0);
    double average = doubleList.stream().mapToDouble(Number::doubleValue).average().getAsDouble();
    double sum = doubleList.stream().mapToDouble(Number::doubleValue).sum();
    double max = doubleList.stream().mapToDouble(Number::doubleValue).max().getAsDouble();
    System.out.println("平均值:" + average + ",总和:" + sum + ",最大值:" + max);

6.reduce

归约,也称缩减,顾名思义,是把一个流缩减成一个值,能实现对集合求和、求乘积和求最值操作。

List<Integer> list = Arrays.asList(1, 3, 2, 8, 11, 4);
		// 求和方式1
		Optional<Integer> sum = list.stream().reduce((x, y) -> x + y);
		
		// 求乘积
		Optional<Integer> product = list.stream().reduce((x, y) -> x * y);

		// 求最大值方式1
		Optional<Integer> max = list.stream().reduce((x, y) -> x > y ? x : y);
		// 求最大值写法2
		Integer max2 = list.stream().reduce(1, Integer::max);

		System.out.println("list求和:" + sum.get() );
		System.out.println("list求积:" + product.get());
		System.out.println("list求最大值:" + max.get() + "," + max2);

list求和:29
list求积:2112
list求最大值:11,11

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"));
		personList.add(new Person("Owen", 9500, 25, "male", "New York"));
		personList.add(new Person("Alisa", 7900, 26, "female", "New York"));

		// 求工资之和方式1:
		Optional<Integer> sumSalary = personList.stream().map(Person::getSalary).reduce(Integer::sum);
		

		// 求最高工资方式1:
		Integer maxSalary = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),
				Integer::max);
		// 求最高工资方式2:
		Integer maxSalary2 = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),
				(max1, max2) -> max1 > max2 ? max1 : max2);
		// 求最高工资方式3:
		Integer maxSalary3 = personList.stream().map(Person::getSalary).reduce(Integer::max).get();

		System.out.println("工资之和:" + sumSalary.get());
		System.out.println("最高工资:" + maxSalary + "," + maxSalary2 + "," + maxSalary3);


工资之和:49300
最高工资:9500,9500

7.collect

归集(toList/toSet/toMap)

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<?, Person> map = personList.stream().filter(p -> p.getSalary() > 8000)
				.collect(Collectors.toMap(Person::getName, p -> p));
		System.out.println("toList:" + listNew);
		System.out.println("toSet:" + set);
		System.out.println("toMap:" + map);
	}

toList:[6, 4, 6, 6, 20]
toSet:[4, 20, 6]
toMap:{Tom=mutest.Person@5fd0d5ae, Anni=mutest.Person@2d98a335}

统计(count/averaging)

计数:count
平均值:averagingInt、averagingLong、averagingDouble
最值:maxBy、minBy
求和:summingInt、summingLong、summingDouble
统计以上所有:summarizingInt、summarizingLong、summarizingDouble

public static void main(String[] args) {
		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"));

		// 求总数
		Long count = personList.stream().collect(Collectors.counting());
		// 求平均工资
		Double average = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));
		// 求最高工资
		Optional<Integer> max = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
		// 求工资之和
		Integer sum = personList.stream().collect(Collectors.summingInt(Person::getSalary));
		// 一次性统计所有信息
		DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));

		System.out.println("员工总数:" + count);
		System.out.println("员工平均工资:" + average);
		System.out.println("员工工资总和:" + sum);
		System.out.println("员工工资所有统计:" + collect);
	}

分组(partitioningBy/groupingBy)

public static void main(String[] args) {
		List<Person> personList = new ArrayList<Person>();
		personList.add(new Person("Tom", 8900, "male", "New York"));
		personList.add(new Person("Jack", 7000, "male", "Washington"));
		personList.add(new Person("Lily", 7800, "female", "Washington"));
		personList.add(new Person("Anni", 8200, "female", "New York"));
		personList.add(new Person("Owen", 9500, "male", "New York"));
		personList.add(new Person("Alisa", 7900, "female", "New York"));

		// 将员工按薪资是否高于8000分组
        Map<Boolean, List<Person>> part = personList.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));
        // 将员工按性别分组
        Map<String, List<Person>> group = personList.stream().collect(Collectors.groupingBy(Person::getSex));
        // 将员工先按性别分组,再按地区分组
        Map<String, Map<String, List<Person>>> group2 = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));
        System.out.println("员工按薪资是否大于8000分组情况:" + part);
        System.out.println("员工按性别分组情况:" + group);
        System.out.println("员工按性别、地区:" + group2);
	}

员工按薪资是否大于8000分组情况:{false=[mutest.Person@2d98a335, mutest.Person@16b98e56, mutest.Person@7ef20235], true=[mutest.Person@27d6c5e0, mutest.Person@4f3f5b24, mutest.Person@15aeb7ab]}
员工按性别分组情况:{female=[mutest.Person@16b98e56, mutest.Person@4f3f5b24, mutest.Person@7ef20235], male=[mutest.Person@27d6c5e0, mutest.Person@2d98a335, mutest.Person@15aeb7ab]}
员工按性别、地区:{female={New York=[mutest.Person@4f3f5b24, mutest.Person@7ef20235], Washington=[mutest.Person@16b98e56]}, male={New York=[mutest.Person@27d6c5e0, mutest.Person@15aeb7ab], Washington=[mutest.Person@2d98a335]}}

接合(joining)

public static void main(String[] args) {
		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"));

		String names = personList.stream().map(p -> p.getName()).collect(Collectors.joining(","));
		System.out.println("所有员工的姓名:" + names);
		List<String> list = Arrays.asList("A", "B", "C");
		String string = list.stream().collect(Collectors.joining("-"));
		System.out.println("拼接后的字符串:" + string);
	}

所有员工的姓名:Tom,Jack,Lily
拼接后的字符串:A-B-C

归约(reducing)

public static void main(String[] args) {
		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"));

		// 每个员工减去起征点后的薪资之和(这个例子并不严谨,但一时没想到好的例子)
		Integer sum = personList.stream().collect(Collectors.reducing(0, Person::getSalary, (i, j) -> (i + j - 5000)));
		System.out.println("员工扣税薪资总和:" + sum);

		// stream的reduce
		Optional<Integer> sum2 = personList.stream().map(Person::getSalary).reduce(Integer::sum);
		System.out.println("员工薪资总和:" + sum2.get());
	}

员工扣税薪资总和:8700
员工薪资总和:23700

8.排序(sorted)

sorted,中间操作。有两种排序:

  • sorted():自然排序,流中元素需实现Comparable接口
  • sorted(Comparator com):Comparator排序器自定义排序
public static void main(String[] args) {
		List<Person> personList = new ArrayList<Person>();

		personList.add(new Person("Sherry", 9000, 24, "female", "New York"));
		personList.add(new Person("Tom", 8900, 22, "male", "Washington"));
		personList.add(new Person("Jack", 9000, 25, "male", "Washington"));
		personList.add(new Person("Lily", 8800, 26, "male", "New York"));
		personList.add(new Person("Alisa", 9000, 26, "female", "New York"));

		// 按工资升序排序(自然排序)
		List<String> newList = personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName)
				.collect(Collectors.toList());
		// 按工资倒序排序
		List<String> newList2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed())
				.map(Person::getName).collect(Collectors.toList());
		// 先按工资再按年龄升序排序
		List<String> newList3 = personList.stream()
				.sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName)
				.collect(Collectors.toList());
		// 先按工资再按年龄自定义排序(降序)
		List<String> newList4 = personList.stream().sorted((p1, p2) -> {
			if (p1.getSalary() == p2.getSalary()) {
				return p2.getAge() - p1.getAge();
			} else {
				return p2.getSalary() - p1.getSalary();
			}
		}).map(Person::getName).collect(Collectors.toList());

		System.out.println("按工资升序排序:" + newList);
		System.out.println("按工资降序排序:" + newList2);
		System.out.println("先按工资再按年龄升序排序:" + newList3);
		System.out.println("先按工资再按年龄自定义降序排序:" + newList4);
	}


按工资升序排序:[Lily, Tom, Sherry, Jack, Alisa]
按工资降序排序:[Sherry, Jack, Alisa, Tom, Lily]
先按工资再按年龄升序排序:[Lily, Tom, Sherry, Jack, Alisa]
先按工资再按年龄自定义降序排序:[Alisa, Jack, Sherry, Tom, Lily]

9. 提取/组合

public static void main(String[] args) {
		String[] arr1 = { "a", "b", "c", "d" };
		String[] arr2 = { "d", "e", "f", "g" };

		Stream<String> stream1 = Stream.of(arr1);
		Stream<String> stream2 = Stream.of(arr2);
		// concat:合并两个流 distinct:去重
		List<String> newList = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());
		// limit:限制从流中获得前n个数据
		List<Integer> collect = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());
		// skip:跳过前n个数据
		List<Integer> collect2 = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList());

		System.out.println("流合并:" + newList);
		System.out.println("limit:" + collect);
		System.out.println("skip:" + collect2);
	}
}


流合并:[a, b, c, d, e, f, g]
limit:[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
skip:[3, 5, 7, 9, 11]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值