JDK8新特性:Stream流(学习笔记)

Stream

什么是Stream?

也叫Stream流,是jdk8新增的API(java.util.stream.*),可以用于操作数组或集合数据。
优势:Stream大量结合了Lambda语法风格来编程,提供了一种更加强大、更加简单的方式操作集合或者数组中的数据,代码更简洁,可读性更好。

Stream流的使用步骤

数据源 集合/数组/…

1.获取Stream流:Stream流代表一条流水线,并能与数据源建立连接。

获取集合的Stream流

Collection提供的如下方法:default Stream stream()
(1)获取List集合的Stream流

		List<String> names = new ArrayList<>();
		Collections.addAll(names,"张三丰","张无忌","周芷若","赵敏","张强");
		Stream<String> stream = names.stream();
		stream.filter(n -> n.contains("张")).forEach(s -> System.out.println(s));

(2)获取Set集合的Stream流

		Set<String> set = new HashSet<>();
		Collections.addAll(set,"刘德华","张曼玉","蜘蛛精","马德","德玛西亚");
		Stream<String> stream1 = set.stream();
		stream1.filter(s -> s.contains("德")).forEach(s -> System.out.println(s));

(3)获取Map集合的Stream流
不能直接用stream方法,需要先把Map变为set集合。

		Map<String,Double> map = new HashMap<>();
		map.put("古力娜扎",172.3);
		map.put("迪丽热巴",168.3);
		map.put("马尔扎哈",166.3);
		map.put("卡尔扎巴",161.3);
		
		// 取key值
		Set<String> keys = map.keySet();
		keys.stream().forEach(s -> System.out.println(s));
		// value
		Collection<Double> values = map.values();
		values.stream().forEach(v -> System.out.println(v));
		// 键值对
		Set<Map.Entry<String, Double>> entries = map.entrySet();
		entries.stream().filter(e -> e.getKey().contains("巴")).forEach(m -> System.out.println(m.getKey()+"->"+m.getValue()));

获取数组Stream流

Arrays类提供如下方法:public static Stream stream(T[] array)
Stream类提供如下方法:public static Stream of(T… valus) 获取当前接受数据的Stream流 可用于数组和集合
获取数组的Stream流

		String[] names2 = new String[]{"张翠山","东方不败","唐大山","孤独求败"};
		Stream<String> s1 = Arrays.stream(names2);
		Stream<String> s2 = Stream.of(names2);

2.Stream流常见的中间方法

中间方法指的是调用完成后会返回新的Stream流,可以继续使用(支持链式编程)。

		List<Double> scores = new ArrayList<>();
		Collections.addAll(scores,88.5,100.0,60.0,99.0,9.5,99.6,25.0);
		// 需求:找出成绩大于等于60分的数据,并升序后,再输出
		scores.stream().filter(s->s>=60).sorted().forEach(s-> System.out.println(s));

重载的sorted方法 Stream sorted(Comparator<? super T> comparator)

        List<Student> students = new ArrayList<>();
        Student s1 = new Student("蜘蛛精",26,172.5);
        Student s2 = new Student("蜘蛛精",26,172.5);
        Student s3 = new Student("蜘蛛精",23,167.5);
        Student s4 = new Student("蜘蛛精",25,169.0);
        Student s5 = new Student("蜘蛛精",35,183.3);
        Student s6 = new Student("蜘蛛精",34,168.5);
        Collections.addAll(students,s1,s2,s3,s4,s5,s6);
        // 需求2:找出年龄大于等于23,且年龄小于等于30岁的学生,并按照年龄降序输出
        students.stream().filter(s -> s.getAge()>=23 && s.getAge()<=30).sorted((o1,o2)->o2.getAge()-o1.getAge()).forEach(s -> System.out.println(s));

取前几个数据 Stream limit(long maxsize)

		 // 需求3:取出身高最高的前3名学生,并输出。limit 取前几个数据
		 students.stream().sorted((o1,o2)-> Double.compare(o2.getHeight(),o1.getHeight())).limit(3).forEach(e -> System.out.println(e));

跳过前几个数据 Stream skip(long n)

		// 需求4:取出身高倒数的2名学生,并输出。 s1,s2,s3,s4,s5,s6。
		students.stream().sorted((o1,o2) -> Double.compare(o2.getHeight(),o1.getHeight())).skip(students.size()-2).forEach(s-> System.out.println(s));

map:映射,类中只保留名字这个属性。distinct:去重复,自定义类型的对象(希望内容一样就认为重复,重写hashCode,equals)

		// 需求5:找出身高超过168学生叫什么名字,要求去除重复的名字,再输出。
        students.stream().filter(s -> s.getHeight()>168).map(Student::getName).distinct().forEach(System.out::println);
        // distinct去重复,自定义类型的对象(希望内容一样就认为重复,重写hashcode,equals)
        students.stream().distinct().forEach(System.out::println);

static Stream concat(Stream a, Stream b) 合并a和b两个流为一个流

		String[] ss1 = new String[]{"张三","李四"};
        String[] ss2 = new String[]{"张三","李四"};
        Stream<String> concat = Stream.concat(Stream.of(ss1), Stream.of(ss2));
        concat.forEach(System.out::println);

3.Stream流常见的终结方法:

终结方法指的是调用完成后,不会返回新的Stream流,没法继续使用流了。

  • void forEach(Consumer action) 对此流运算后的元素执行遍历 long count()
  • 统计此流运算后的元素个数 Optional max(Comparator<? super T> comparator)
  • 获取此流运算后最大值元素 Optional min(Comparator<? super T> comparator)
  • 获取此流运算后的最小值元素
public class StreamFinal {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        Student s1 = new Student("蜘蛛精",26,172.5);
        Student s2 = new Student("蜘蛛精",26,172.5);
        Student s3 = new Student("紫霞",23,167.6);
        Student s4 = new Student("白晶晶",25,169.0);
        Student s5 = new Student("牛魔王",35,183.3);
        Student s6 = new Student("牛夫人",34,168.5);
        Collections.addAll(students,s1,s2,s3,s4,s5,s6);

        //需求1:请计算出身高超过168的学生有几人。
        long count = students.stream().filter(s -> s.getHeight() > 168).count();
        System.out.println(count);

        //需求2:请找出身高最高的学生对象,并输出
        Student s = students.stream().max((o1, o2) -> Double.compare(o1.getHeight(), o2.getHeight())).get();
        System.out.println(s);

        //需求3:请找出身高最矮的学生对象,并输出
        Student ss = students.stream().min((o1,o2) -> Double.compare(o1.getHeight(),o2.getHeight())).get();
        System.out.println(ss);
    }
}
  • 收集Stream流:就是把Stream流操作后的结果转回到集合或者数组中去返回。
  • Stream流:方便操作集合/数组的手段;集合/数组:才是开发中的目的。
    R collect(Collector collector) 把流处理后的结果收集到一个指定的集合中去
    Object[] toArray() 把流处理后的结果收集到一个数组中去流只能收集一次
		// 需求4:请找出身高超出170的学生对象,并放到一个新集合中去返回。
        List<Student> list = students.stream().filter(h -> h.getHeight() > 170).collect(Collectors.toList());
        System.out.println(list);·

        //需求5:请找出身高超过170的学生对象,并把学生对象的名字和身高,存入到一个新集合返回
        Set<Student> setstudent = students.stream().filter(h -> h.getHeight() > 170).collect(Collectors.toSet());
        System.out.println(setstudent);

        //需求5:请找出身高超过170的学生对象,并把学生对象的名字和身高,存入到一个map集合返回
        Map<String, Double> map = students.stream().filter(h -> h.getHeight() > 170).distinct().collect(Collectors.toMap(a -> a.getName(), a -> a.getHeight()));
        System.out.println(map);

        Object[] objects = students.stream().toArray();
        Student[] arr = students.stream().toArray(len -> new Student[len]);
        System.out.println(Arrays.toString(objects));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值