Lambda expression and Stream stream processing

1. Advantages of Lambda expressions

1) JDK8 began to support Lambda expressions to make programming more elegant

2) Anonymous inner classes and function declarations and calls can be realized more concisely by using Lambda

3) Stream processing based on Lambda greatly simplifies operations on collections

        Implement collection sorting legacy code

        List<String> names = Arrays.asList("peter","anna","mike");
        Collections.sort(names, new Comparator<String>() {
            @Override
            public int compare(String a, String b) {
                return b.compareTo(a);
            }
        });

        Use Lambda expressions to achieve the above functions

        List<String> names = Arrays.asList("peter","anna","mike");
        Collections.sort(names, (a, b) -> b.compareTo(a));

Two, Lambda expression syntax format

        Lambda expressions can only implement interfaces with one and only one abstract method, called functional interfaces 

3. Functional programming

        Functional programming is a programming style based on functional interfaces and expressed using lambdas.

        The idea of ​​functional programming is to bring code into execution as reusable data . Functional programming emphasizes "what do you want to do" rather than "how do you want to do it". as follows

    public void test(){
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9);
        filter(list, n -> n%2 == 1);
        filter(list, n -> n%2 == 0);
    }
    public static void filter(List<Integer> list, Predicate<Integer> predicate) {
        for (Integer num: list) {
            if(predicate.test(num)){
                System.out.printf(num+"");
            }
        }
    }

        A functional interface is an interface with one and only one abstract method. There are a large number of functional interfaces in Java, such as java.lang.Runnable. Java8 provides a series of new functional interfaces, located in java.util.function.

        Predicate<T>: Receives a parameter and returns a Boolean value, which is used to test whether the incoming data meets the judgment requirements. Predicate needs to implement the test() method for logical judgment.

       Consumer<T> : Receives a parameter, does not return a result, and has an accept method.

       IntConsumer : Consumer whose parameter is an integer

        Function<T,R> : Receive a parameter and need to return data, there is an apply method

        When customizing a functional interface, you can use the @FunctionalInterface annotation to inform the compiler that this is a functional interface, and you can check the abstract method or not.

4. Comparison of functional programming and object-oriented programming

Five, Stream stream processing

        Stream stream processing is a multi-data processing technology based on Lambda. Stream highly abstracts collection data processing and greatly simplifies the amount of code. Stream can perform a series of processing such as iteration, de-duplication, filtering, sorting, and aggregation on the collection.

//        获取List集合中最大的偶数
        Optional<Integer> op = Arrays.asList(1,2,3,4,5,6,7,8,9).stream()
                .filter(x -> x%2 == 0)
                .sorted((a,b) -> b-a)
                .findFirst();
        System.out.println(op.get());

        Common methods of stream processing

 collect: Collect streaming data and generate a new List/Set 

        method usage example

        // 偶数求和        
        List<String> list = Arrays.asList("1","2","3","4");
        int sum = list.stream()
                .mapToInt(s -> Integer.parseInt(s))
                .filter(num -> num%2 == 0)
                .sum();
        // 首字母转大写
        List<String> list = Arrays.asList("lily","andy","jack","smith");
        List<String> result = list.stream()
                .map(s -> s.substring(0,1).toUpperCase() + s.substring(1))
                .collect(Collectors.toList());
         // 将所有奇数从小到大排序,且不许出现重复
        List<Integer> list = Arrays.asList(11, 2, 38, 4, 52, 6, 7, 11);
        List<Integer> result = list.stream()
                .distinct()     //去除重复流数据
                .filter( n -> n%2 == 1)
                .sorted((a,b) -> b-a)       //排序
                .collect(Collectors.toList());

6. Five ways to create stream objects

1) Create based on an array

String[] arr = {"Lily", "Andy", "Jackson"};
Stream<String> stream = Stream.of(arr);
stream.forEach(s -> System.out.println(s));

2) Create based on collection 

List<String> list = new ArrayList<>();
list.add("Lily");
list.add("Andy");
Stream stream = list.stream();

3) Use the generate method to create an infinite length stream

Stream<Integer> stream = Stream.generate(() -> new Random().nextInt(100000));
stream.limit(10).forEach(i -> System.out.println(i));

4) Create a stream based on an iterator

Stream<Integer> stream = Stream.iterate(1, n -> n+1).limit(100);

5) Create a stream based on a sequence of characters 

// 可以处理汉字,会自动转为unicode码
String str = "abcdefg嘿嘿";
IntStream stream = str.chars();
stream.forEach(c -> System.out.println((char)c));

Guess you like

Origin blog.csdn.net/qq_33235279/article/details/130214367