java函数式编程Consumer,Supplier,Function
代码示例
@Slf4j public class DemoJavaFunction { public static void main(String[] args) { // 第一步:模拟入参数据的准备 Supplier<DemoJavaFunction.DemoInput> supplier = ()->{ DemoJavaFunction.DemoInput input = new DemoJavaFunction.DemoInput(); input.setId(100); input.setInputMsg("inputMsg_value"); input.setMsg("消息"); input.setFlag(true); return input; }; //第二步:Function作用:函数编程入参和业务中间数据流的转换 Function<DemoJavaFunction.DemoInput, DemoJavaFunction.DemoDto> function = input -> { DemoJavaFunction.DemoDto demoDto = new DemoJavaFunction.DemoDto(); demoDto.setMsg(input.getMsg()+":Function"); demoDto.setId(input.getId()); demoDto.setInputMsg("数据正在处理"); demoDto.setInterState("中间状态"); return demoDto; }; //第三步:出参数据业务操作 DemoJavaFunction.DemoOutput output = new DemoJavaFunction.DemoOutput(); Consumer<DemoJavaFunction.DemoDto> consumer = input -> { log.info("Consumer flag is true input:{}", input); output.setId(input.getId()); output.setMsg(input.getMsg()); output.setInterState(input.getInterState()); output.setFlag(input.getFlag()); output.setOutputFlag("OutputFlag出参数"); }; //第四步:业务逻辑调用 BiConsumer<Consumer<DemoJavaFunction.DemoDto>, DemoJavaFunction.DemoDto> biConsumer = (callback, value) -> { for(int i = 0; i < 10; i++){ //回调第三步操作 callback.accept(value); } }; //第五步:注意生产者到双向消费者执行过程 biConsumer.accept(consumer, function.apply(supplier.get())); log.info("output:{}", output); //断言操作 Predicate<String> predicate = (x)-> "A".equals(x); System.out.println(predicate.test("B")); } @Data @NoArgsConstructor @AllArgsConstructor static class DemoEntity{ private Integer id; private String msg; private Boolean flag; } @Data @NoArgsConstructor @AllArgsConstructor static class DemoInput{ private Integer id; private String msg; private Boolean flag; private String inputMsg; } @Data @NoArgsConstructor @AllArgsConstructor static class DemoDto{ private Integer id; private String msg; private Boolean flag; private String inputMsg; private String interState; } @Data @NoArgsConstructor @AllArgsConstructor static class DemoOutput{ private Integer id; private String msg; private Boolean flag; private String interState; private String outputFlag; } }
美梦成真,变为事实。