有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (1) 个答案

  1. # 1 楼答案

    您可以使用8以上版本的Java,然后takeWhiledropWhile

    import java.util.stream.Stream;
    
    public class Temp {
        public static void main(String [] args){
            Stream
                    //Generate a stream of arrays like this {0,1}, {1, 1}, {1, 2}, {2, 3}, {3, 5}...etc.
                    .iterate(new int[] { 0, 1 }, f -> new int[] { f[1], f[0] + f[1] })
                    //Keep only the 1st element of each array.
                    .map(n -> n[0])
                    //Drop only 0.
                    .dropWhile(i -> i < 1)
                    //Take any number which is <= 100.
                    .takeWhile(i -> i <= 100)
                    .forEach(System.out::println);
        }
    
    }
    

    当然,使用{ 1, 2 }作为种子可以避免dropWhile

    Java8没有提供一种基于谓词的方式来限制/停止流,所以我坚持使用该版本的循环