JDK新特性-Stream流

Stream流是用来操作集合或者数组中的数据的,Stream流提供了一种更加强大的,更加简单的方式来操作集合或者数组中的数据,代码更加简洁,可读性更好。下面是一个简单的例子:

public class S1 {

    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        Collections.addAll(names, "张三丰", "张无忌", "周芷若", "赵敏", "张强");
        System.out.println(names);


        // 找出姓张的,且名字是三个字的存入到新集合中去
        System.out.println(getZ3(names));

        // 使用Stream流实现上述需求
        List<String> list = names.stream()
                .filter(s -> s.startsWith("张"))
                .filter(s -> s.length()==3)
                .collect(Collectors.toList());
        System.out.println(list);
    }

    static List<String> getZ3(List<String> names){
        List<String> newNames = new ArrayList<>();
        // 遍历集合,然后匹配姓张且为三个字的将其添加到新的集合中去
        for (String name : names) {
            if (name.length()==3 && name.startsWith("张")){
                newNames.add(name);
            }
        }
        return newNames;
    }

}

关于Stream流操作数据的描述:Stream流就像是一条流水线,能够跟数据建立连接,然后调用流水线上的各种方法对数据进行处理、计算等,最后获取处理的结果,遍历、统计、收集到一个新集合中返回。

Stream流常见的中间方法:

运用不同中间方法的例子:

        // 需求1:对包含分数的集合,找出大于60的,并进行升序排序后输出
        List<Double> list1 = new ArrayList<>();
        Collections.addAll(list1, 59.0, 80.0, 80.1, 85.2, 79.0, 60.0, 90.0, 86.9);
        list1.stream().filter(s -> s >= 60).sorted().forEach(s -> System.out.println(s));

        // 需求2:找出年龄大于等于23,且年龄小于等于30岁的学生,并按照年龄降序输出
        List<Student> students = new ArrayList<>();
        Student s1 = new Student("张三", 31, 172.1);
        Student s2 = new Student("李四", 27, 180.2);
        Student s3 = new Student("王五", 23, 179.0);
        Student s4 = new Student("赵六", 30, 171.0);
        Student s5 = new Student("赵六", 33, 178.0);
        Collections.addAll(students, s1, s2, s3, s4, s5);

        students.stream().filter(student -> student.age>=23 && student.age<=30).sorted(((o1, o2) -> o2.age - o1.age))
                .forEach(student -> System.out.println(student));

        // 需求3:找出身高前三名的学生输出
        students.stream().sorted(((o1, o2) -> Double.compare(o2.height, o1.height))).limit(3)
                .forEach(student -> System.out.println(student));

        // 需求4:取出身高最矮的两位同学的信息
        System.out.println("最矮的两位同学:");
        students.stream().sorted((o1, o2) -> Double.compare(o1.height, o2.height)).limit(2)
                .forEach(student -> System.out.println(student));

        // 需求5:找出身高超过168的学生的名字,要求去除重复的名字,再输出
        students.stream().filter(student -> student.height>168).map(student -> student.name).distinct()
                .forEach(s -> System.out.println(s));

Stream流常见的终结方法:终结方法是指这些方法调用之后就不会继续返回Stream流了

运用stream流终结方法的例子 

        List<Student> students = new ArrayList<>();
        Student s1 = new Student("张三", 31, 162.1);
        Student s2 = new Student("李四", 27, 180.2);
        Student s3 = new Student("王五", 23, 179.0);
        Student s4 = new Student("赵六", 30, 171.0);
        Collections.addAll(students, s1, s2, s3, s4);

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

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

        // 需求3:找出身高最矮的学生对象
        Student ss = students.stream().min(((o1, o2) -> Double.compare(o1.height, o2.height))).get();
        System.out.println(ss);

        // 需求4:找出身高超过170的学生对象,并放到一个新集合中去返回
        List<Student> students1 = students.stream().filter(student -> student.height > 170).collect(Collectors.toList());
        System.out.println(students1);

        // 需求5:找出身高超过170的学生对象,并将其名字和身高放入到一个Map集合中返回
        Map<String, Double> stringDoubleMap = students.stream().filter(student -> student.height > 170).collect(Collectors.toMap(a -> a.name, a -> a.height));
        System.out.println(stringDoubleMap);

        // 将学生对象收集到数组中去
        Student[] students2 = students.stream().toArray(len -> new Student[len]);
        System.out.println(Arrays.toString(students2));

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
# jdk7特性 ## try-with-resources 是一种声明了`一种或多种资源的try语句`。资源是指在程序用完了之后必须要关闭的对象。try-with-resources语句保证了每个声明了的`资源在语句结束的时候都会被关闭`。任何实现了java.lang.`AutoCloseable`接口的对象,和实现了java .io .`Closeable`接口的对象,`都可以当做资源使用`。 ``` try ( InputStream is = new FileInputStream("xx"); OutputStream os = new FileOutputStream("xx") ) { //xxx //不用关闭了,JVM帮你关闭 ``` ## 多异常统一处理 在Java 7中,catch代码块得到了升级,用以在`单个catch块中处理多个异常`。如果你要捕获多个异常并且它们包含相似的代码,使用这一特性将会减少代码重复度。 ``` try { //xxx } catch (AException | BException e) { e.printStackTrace(); } ``` 缺点是异常处理细粒度降低 ## 泛型推导 ``` List<String> list = new ArrayList<>(); ``` `泛型实例`的创建可以通过`类型推断`来简化,`可以去掉`后面new部分的泛型类型,`只用<>`就可以了。 ## 使用ForkJoin Java 7开始引入了一种的Fork/Join线程池,它可以执行一种特殊的任务:把一个大任务拆成多个小任务并行执行。 我们举个例子:如果要计算一个超大数组的和,最简单的做法是用一个循环在一个线程内完成: ```ascii ┌─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┐ └─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┘ ``` 还有一种方法,可以把数组拆成两部分,分别计算,最后加起来就是最终结果,这样可以用两个线程并行执行: ```ascii ┌─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┐ └─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┘ ┌─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┐ └─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┘ ``` 如果拆成两部分还是很大,我们还可以继续拆,用4个线程并行执行: ```ascii ┌─┬─┬─┬─┬─┬─┐ └─┴─┴─┴─┴─┴─┘ ┌─┬─┬─┬─┬─┬─┐ └─┴─┴─┴─┴─┴─┘ ┌─┬─┬─┬─┬─┬─┐ └─┴─┴─┴─┴─┴─┘ ┌─┬─┬─┬─┬─┬─┐ └─┴─┴─┴─┴─┴─┘ ``` 这就是Fork/Join任务的原理:判断一个任务是否足够小,如果是,直接计算,否则,就分拆成几个小任务分别计算。这个过程可以反复“裂变”成一系列小任务。 我们来看如何使用Fork/Join对大数据进行并行求和: ``` public class Main { public static void main(String[] args) throws Exception { // 创建2000个随机数组成的数组: long[] array = new long[2000]; long expectedSum = 0; for (int i = 0; i < array.length; i++) { array[i] = random(); expectedSum += array[i]; } System.out.println("Expected sum: " + expectedSum); // fork/join: ForkJoinTask<Long> task = new SumTask(array, 0, array.length); long startTime = System.currentTimeMillis(); Long result = ForkJoinPool.commonPool().invoke(task); long endTime = System.currentTimeMillis(); System.out.println("Fork

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冉冉编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值