Java Fibonacci Sequence Stream Use

Preface

When I was studying the code today, I saw the use of streams, so I found a few technical articles about streams on the Internet, run them, and make a record

**

1. What is the Fibonacci sequence?

**

Each number is the sum of the previous two numbers
such as 1,1,2,3,5,8,13,21,34,55

**

2. Implementation code

**
Code One:

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");
        }
    }

Code two:

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");
        }
   }

Code three: (recursive writing)

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");
        }
    }
}

Code four: (stream operation)

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. Extension of knowledge

Java 8 stream usage

1. Create a stream

Collection creation

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

Array creation

 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);

The of() method actually calls the Arrays.stream() method inside.

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); //生成两个随机数

Convert each line of the file into a stream

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){
    
    
         
     }
 }

Separate strings into streams

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. Operation flow

Screening and slicing

filter: filter some elements in the stream
limit(n): get n elements
skip(n): skip n elements, with limit(n) can realize paging
distinct: pass the hashCode() and equals() of the elements in the stream Remove duplicate elements

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);
    }

Class name: The method name is a new syntax introduced by Java 8. System.out returns the PrintStream class, and the println method prints

Mapping

map: Receive a function as a parameter, the function will be applied to each element, and map it into a new element.
flatMap: Receive a function as a parameter, replace each value in the stream with another stream, and then connect all streams into one stream.

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}            

Sort

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);
    }

match

anyMatch: true
if there is one match allMatch: true if all matches
noneMatch: true if none matches

 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
    }

Element combination

 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. Stream conversion

Circulation array

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

Circulation collection

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

4. Reference link

Three ways to print Fibonacci numbers using Java
The detailed usage of Java 8 stream will
take you to the Java Stream stream, which is too strong

Guess you like

Origin blog.csdn.net/qq_36636312/article/details/108356262