码迷,mamicode.com
首页 > 编程语言 > 详细

Java-学习日记(函数式编程与@ControllerAdvice)

时间:2020-09-24 20:49:34      阅读:34      评论:0      收藏:0      [点我收藏+]

标签:str   runnable   list   org   tor   java   添加   optional   tps   

函数式编程:

函数可以作为变量、参数、返回值和数据类型

相关内容有@FunctionalInterface(Runnable、Comparator内部添加了),Lambda和函数式接口

感觉上面这句话就说的很有道理,下面针对普通函数,lambda和具体内部实现来说下

普通函数
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("do something");
            }
        };
Lambda

从上面内部类和下面函数式接口可以看出,Lambda其实就是在函数式接口上进一步简化了代码

Runnable runnable = () -> System.out.println("do Something");
Optional<Integer> result = Stream.of("a", "be", "hello")
                .map(s -> s.length())
                .filter(l-> l <= 3)
                .max((o1, o2) ->  o1-o2);
        System.out.println(result.get());
内部函数式接口
Optional<Integer> result = Stream.of("a", "be", "hello")
                //功能性接口:类型转换
                .map(new Function<String, Integer>() {
                    @Override
                    public Integer apply(String s) {
                        return s.length();
                    }
                })
                //谓语性接口:返回bool值
                .filter(new Predicate<Integer>() {
                    @Override
                    public boolean test(Integer integer) {
                        return integer <= 3;
                    }
                })
                //comparator比较器(对象内部比较还可以实现Comparable接口),o1-o2是升序,1,2输出2,若是o2-o1则是逆序,输出1
                .max(new Comparator<Integer>() {
                    @Override
                    public int compare(Integer o1, Integer o2) {
                        return o1 - o2;
                    }
                });
        System.out.println(result.get());
package lambda;

import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;

/**
 * @ProjectName: Method
 * @Package: lambda
 * @Description:
 * @Author: huyuqiao
 * @CreateDate: 2020/9/22 9:17
 */
public class Method {
    private static void oldFunction(){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("do something");
            }
        };
    }
    private static void newFunction(){
        Runnable runnable = () -> System.out.println("do Something");
    }
    private static void optionalFunction(){
        Optional<Integer> result = Stream.of("a", "be", "hello")
                .map(s -> s.length())
                .filter(l-> l <= 3)
                .max((o1, o2) ->  o1-o2);
        System.out.println(result.get());
    }
    /*这个函数是上面的全写,上面函数进行了简化*/
    private static void optionalFunction_2(){
        Optional<Integer> result = Stream.of("a", "be", "hello")
                //功能性接口:类型转换
                .map(new Function<String, Integer>() {
                    @Override
                    public Integer apply(String s) {
                        return s.length();
                    }
                })
                //谓语性接口:返回bool值
                .filter(new Predicate<Integer>() {
                    @Override
                    public boolean test(Integer integer) {
                        return integer <= 3;
                    }
                })
                //comparator比较器(对象内部比较还可以实现Comparable接口),o1-o2是升序,1,2输出2,若是o2-o1则是逆序,输出1
                .max(new Comparator<Integer>() {
                    @Override
                    public int compare(Integer o1, Integer o2) {
                        return o1 - o2;
                    }
                });
        System.out.println(result.get());
    }

    private static void compareFunction(){
        List<User> users = new ArrayList<>();
        users.add(new User(2, "asdf", "sadf"));
        users.add(new User(1, "asdf", "sadf"));
        Collections.sort(users, new Comparator<User>() {
            @Override
            public int compare(User o1, User o2) {
                return Integer.compare(o2.getId(), o1.getId());
            }
        });
        users.stream().forEach(System.out::println);
    }

    private static void compareFunction_2(){
        List<User> users = new ArrayList<>();
        users.add(new User(2, "asdf", "sadf"));
        users.add(new User(1, "asdf", "sadf"));
        //定义比较器
        Comparator<User> comparator = (u1, u2) -> Integer.compare(u1.getId(), u2.getId());
        users.sort(comparator);
        users.stream().forEach(System.out::println);
    }

    public static void main(String[] args){  
/*        oldFunction();
        newFunction();
        optionalFunction();
        optionalFunction_2();*/

//        compareFunction();
        compareFunction_2();


    }
}

之前写的四个函数式接口: https://www.cnblogs.com/meditation5201314/p/13693089.html

@ControllerAdvice

SpringMvc:@ControllerAdvice具备下面3个功能:

  1. 全局异常处理
  2. 全局数据绑定
  3. 全局数据预处理

前面2个好理解,最后一个数据预处理在传递多个参数的时候,如果遇到变量名相同,后台就无法区分,所以需要配置进行区分(之前好像都没遇到过,记录一下)

给出两个相同类,Controller层里面就要进行区分(postman中就要使用u.userName,p.userName来进行区分,否则什么都不写的话原来默认就是全部覆盖.)

    @PostMapping("/book")
    public void addBook(@ModelAttribute("u") User user, @ModelAttribute("p")Person person, Model model){
        System.out.println(user);
        System.out.println(person);
        Map<String, Object> map = model.asMap();
        System.out.println(map);
    }
package huyuqiao.exception;

import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: GloabalExceptionHandler
 * @Package: huyuqiao.exception
 * @Description:
 * @Author: huyuqiao
 * @CreateDate: 2020/9/22 19:01
 */
@ControllerAdvice
public class GloabalExceptionHandler {
    /*全局异常处理---可以改成NullPointerException异常处理*/
    @ExceptionHandler(Exception.class)
    public ModelAndView customException(Exception e) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("message", e.getMessage());
        mv.setViewName("myerror");
        return mv;
    }

    /*全局数据绑定*/
    @ModelAttribute(name = "md")
    public Map<String,Object> mydata() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("age", 99);
        map.put("gender", "男");
        return map;
    }

    /*全局数据预处理*/
    @InitBinder("u")
    public void u(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("u.");
    }
    @InitBinder("p")
    public void p(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("p.");
    }
}

Java-学习日记(函数式编程与@ControllerAdvice)

标签:str   runnable   list   org   tor   java   添加   optional   tps   

原文地址:https://www.cnblogs.com/meditation5201314/p/13714417.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!