Javaフィボナッチ数列ストリームの使用

序文

今日コードを勉強していたとき、ストリームの使用を見たので、インターネット上のストリームに関するいくつかの技術記事を見つけて実行し、記録を作成しました

****

1.フィボナッチ数列とは何ですか?

****

各数値は、
1,1,2,3,5,8,13,21,34,55などの前の2つの数値の合計です。

****

2.実装コード

**
コード1:

public static void main(String[] args) {
    
    
        // a,b,c
        int a = 1;
        int b = 1;
        int c = 0;
        System.out.print(a + "\t" + b + "\t");
        for (int i = 3; i <= 10; i++) {
    
    
            // 每次运算之后,将数值向后移位
            c = a + b;
            a = b;
            b = c;
            System.out.print(c + "\t");
        }
    }

コード2:

public static void main(String[] args) {
    
    
        int[] arr = new int[10];
        arr[0] = 1;
        arr[1] = 1;
        for(int i = 0;i < arr.length;i++) {
    
    
            if(i > 1) {
    
    
                arr[i] = arr[i - 2] + arr[i - 1];
            }
            System.out.print(arr[i] + "\t");
        }
   }

コード3 :(再帰的記述)

public class PrintFib {
    
    
    public static int fib(int num) {
    
    
        if(num == 1 || num == 2) {
    
    
            return 1;
        }else {
    
    
            return fib(num - 2) + fib(num - 1);
        }
    }

    //主函数(程序入口)
    public static void main(String[] args) {
    
    
        for(int i = 1;i <= 10;i++) {
    
    
            System.out.print(fib(i) + "\t");
        }
    }
}

コード4 :(ストリーム操作)

public static void main(String[] args) {
    
    
       Stream.iterate(new int[]{
    
    0, 1}, n -> new int[]{
    
    n[1], n[0] + n[1]})
               .limit(10)
               .map(n -> n[1])
               .forEach(x -> System.out.print(x+ ","));
   }

3.知識の拡張

Java8ストリームの使用

1.ストリームを作成します

コレクションの作成

 List<String> list = new ArrayList<>();
 Stream<String> stream = list.stream(); //获取一个顺序流
 Stream<String> parallelStream = list.parallelStream(); //获取一个并行流

アレイの作成

 Integer[] arrs = new Integer[]{
    
    1,2,3,4,5,6};
 Stream<Integer> stream = Arrays.stream(arrs);
 stream = Stream.of(1,2,3,4,5,6);

of()メソッドは、実際には内部のArrays.stream()メソッドを呼び出します。

Stream<Integer> stream2 = Stream.iterate(0, (x) -> x + 2).limit(6);
stream2.forEach(System.out::print); // 0 2 4 6 8 10

Stream<Double> stream3 = Stream.generate(Math::random).limit(2);
stream3.forEach(System.out::print); //生成两个随机数

ファイルの各行をストリームに変換します

public static void main(String[] args) {
    
    
    try {
    
    
         BufferedReader reader = new BufferedReader(new FileReader("F:\\test_stream.txt"));
         Stream<String> lineStream = reader.lines();
         lineStream.forEach(System.out::println);
     }catch (Exception e){
    
    
         
     }
 }

文字列をストリームに分割する

public static void main(String[] args) {
    
    
    Pattern pattern = Pattern.compile(",");
    Stream<String> stringStream = pattern.splitAsStream("a,b,c,d");
    stringStream.forEach(System.out::print);//abcd
}

2.操作フロー

スクリーニングとスライス

filter:ストリーム内のいくつかの要素をフィルタリングします
limit(n):n個の要素を取得します
skip(n):n個の要素をスキップします。limit(n)を使用すると、ページングを
区別できます。ストリーム内の要素のhashCode()とequals()を渡します。重複する要素を削除する

public static void main(String[] args) {
    
    
        Stream<Integer> stream = Stream.of(1, 3, 5, 7, 8, 8, 9, 10);
        Stream<Integer> newStream = stream.filter(s -> s > 5) //7 8 8 9 10
                .distinct()  //7 8 9 10
                .skip(2) //9 10
                .limit(2); //9 10
        newStream.forEach(System.out::println);
    }

クラス名:メソッド名は、Java 8によって導入された新しい構文です。System.outはPrintStreamクラスを返し、printlnメソッドは出力します。

マッピング

map:関数をパラメーターとして受け取ります。関数は各要素に適用され、新しい要素にマップされます。
flatMap:関数をパラメーターとして受け取り、ストリーム内の各値を別のストリームに置き換えてから、すべてのストリームを1つのストリームに接続します。

public static void main(String[] args) {
    
    
        List<String> list = Arrays.asList("a,b,c", "1,2,3");

        Stream<String> s1 = list.stream().map(s -> s.replaceAll(",", ""));
        s1.forEach(System.out::println); // abc  123

        Stream<String> s3 = list.stream().flatMap(s -> {
    
    
            Stream<String> s2 = Arrays.stream(s.split(","));
            return s2;
        });
        s3.forEach(System.out::println); // a b c 1 2 3
    }
// 把 Stream<String> 的流转成一个 Stream<Integer> 的流。
 public static void main(String[] args) {
    
    
        List<String> list = new ArrayList<>();
        list.add("0");
        list.add("00");
        list.add("000");
        Stream<Integer> stream = list.stream().map(String::length);
        stream.forEach(System.out::println);// 1 2 3
    }
// peek:如同于map,能得到流中的每一个元素。
// 但map接收的是一个Function表达式,有返回值;
// 而peek接收的是Consumer表达式,没有返回值。

Student s1 = new Student("aa", 10);
Student s2 = new Student("bb", 20);
List<Student> studentList = Arrays.asList(s1, s2);
 
studentList.stream()
        .peek(o -> o.setAge(100))
        .forEach(System.out::println);   
 
//结果:
Student{
    
    name='aa', age=100}
Student{
    
    name='bb', age=100}            

ソート

public static void main(String[] args) {
    
    
        List<String> list = Arrays.asList("aa", "ff", "dd");
        list.stream().sorted().forEach(System.out::println);// aa dd ff

        Student s1 = new Student("a", 1);
        Student s2 = new Student("b", 2);
        Student s3 = new Student("c", 3);
        List<Student> studentList = Arrays.asList(s1, s2, s3);

        //先按姓名升序,姓名相同则按年龄升序
        studentList.stream().sorted(
                (o1, o2) -> {
    
    
                    if (o1.getName().equals(o2.getName())) {
    
    
                        return o1.getAge() - o2.getAge();
                    } else {
    
    
                        return o1.getName().compareTo(o2.getName());
                    }
                }
        ).forEach(System.out::println);
    }

一致

anyMatch:一致するものが1つある
場合はtrue allMatch:すべてが一致する
場合はtrue noneMatch:一致するものがない場合はtrue

 public static void main(String[] args) {
    
    
        List<String> list = new ArrayList<>();
        list.add("11");
        list.add("12");
        list.add("13");
        boolean  anyMatchFlag = list.stream().anyMatch(element -> element.contains("2"));
        boolean  allMatchFlag = list.stream().allMatch(element -> element.length() > 1);
        boolean  noneMatchFlag = list.stream().noneMatch(element -> element.endsWith("0"));
        System.out.println(anyMatchFlag);//true
        System.out.println(allMatchFlag);//true
        System.out.println(noneMatchFlag);//true
    }

要素の組み合わせ

 public static void main(String[] args) {
    
    
            Integer[] ints = {
    
    0, 1, 2, 3};
            List<Integer> list = Arrays.asList(ints);

            // 无初始值,数组求和
            Optional<Integer> a1 = list.stream().reduce((a, b) -> a + b);
            Optional<Integer> b1 = list.stream().reduce(Integer::sum);
            System.out.println(a1.orElse(0));//6
            System.out.println(b1.orElse(0));//6

            //有初始值,初始值相加
            int a11 = list.stream().reduce(6, (a, b) -> a + b);
            System.out.println(a11);//12
            int b11 = list.stream().reduce(6, Integer::sum);
            System.out.println(b11);//12
        }

3.ストリーム変換

循環アレイ

 String[] strArray = list.stream().toArray(String[]::new);

循環コレクション

 List<Integer> list1 = list.stream().map(String::length).collect(Collectors.toList());
 List<String> list2 = list.stream().collect(Collectors.toCollection(ArrayList::new));

4.参照リンク

Javaを使用してフィボナッチ数を印刷する3つの方法Java8
ストリームの詳細な使用法により
、強すぎるJavaストリームストリームに移動します。

おすすめ

転載: blog.csdn.net/qq_36636312/article/details/108356262