zoukankan      html  css  js  c++  java
  • 数值流

    
    import java.util.Arrays;
    import java.util.List;
    import java.util.OptionalInt;
    import java.util.stream.IntStream;
    import java.util.stream.Stream;
    
    
    /**
     * 数值流
     */
    public class MapDemo3 {
        public static void main(String[] args){
            List<Apple> appleList = Arrays.asList(new Apple("red",12),new Apple("yellow",15),new Apple("green",10),new Apple("red",10));
            //映射到数值流
            //IntStream还支持其他的方便方法,如max、min、average等。
            int sumWeight = appleList.stream()
                    .mapToInt(Apple::getWeight)
                    .sum();
            System.out.println(sumWeight);
            //原始流转换成一般流
            IntStream intStream = appleList.stream()
                    .mapToInt(Apple::getWeight);//将 Stream 转 换为数值流
            Stream<Integer> boxed = intStream.boxed();//将数值流转 换为Stream
            //默认值OptionalInt
            OptionalInt optionalInt = appleList.stream()
                    .mapToInt(Apple::getWeight)
                    .max();
            int max = optionalInt.orElse(-1);
            System.out.println(max);//如果没有最大值的话,显式提供一个默认最大值
    
            //数值范围
            //Java 8引入了两个可以用于IntStream和LongStream的静态方法,帮助生成这种范围: range和rangeClosed。这两个方法都是第一个参数接受起始值,第二个参数接受结束值。但 range是不包含结束值的,而rangeClosed则包含结束值
            IntStream intStream1 = IntStream.rangeClosed(1, 100)
                    .filter(n -> n % 2 == 0);
            System.out.println(intStream1.count());//从1到100 偶数个数
    
    
        }
    }
    
    
    import java.util.stream.IntStream;
    import java.util.stream.Stream;
    
    /**
     * 勾股数
     */
    public class MapDemo4 {
        public static void main(String[] args) {
            Stream<double[]> pythagoreanTriples = IntStream.rangeClosed(1, 100)//从rangeClosed返回的IntStream生成一个IntStream
                    .boxed()//生成Stream<Integer>
                    .flatMap(a ->  //flatMap把所有生成的三元数流扁平化成一个流
                            IntStream.rangeClosed(a, 100)
                                    .mapToObj(b -> new double[]{a, b, Math.sqrt(a * a + b * b)})//返回一个对象值流
                                    .filter(t -> t[2] % 1 == 0));//元组中的第三个元素必须是整数
    
            pythagoreanTriples.limit(5) //明确限定从生成的流 中要返回多少组勾股数
                    .forEach(t->System.out.println(t[0] + ", " + t[1] + ", " + t[2]));
    
            //3.0, 4.0, 5.0
            //5.0, 12.0, 13.0
            //6.0, 8.0, 10.0
            //7.0, 24.0, 25.0
            //8.0, 15.0, 17.0
        }
    }
    
  • 相关阅读:
    Linux命令-网络命令:netstat
    Linux命令-网络命令:traceroute
    Linux命令-网络命令:lastlog
    Linux命令-网络命令:last
    mongodb3.4 安装及用户名密码设置
    MySQL表名不区分大小写的设置方法
    数据库设计中的四个范式
    dubbo本地调试直连
    com.mysql.jdbc.PacketTooBigException: Packet for query is too large (1169 > 1024)
    Linux服务器时间同步
  • 原文地址:https://www.cnblogs.com/fly-book/p/12651372.html
Copyright © 2011-2022 走看看