1 Star 0 Fork 0

Jay/JavaStudy

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
ExecuteAround.java 1.63 KB
一键复制 编辑 原始数据 按行查看 历史
liangzj1630@163 提交于 4年前 . JavaInAction chap05
package com.study.chap3;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
* 环绕执行场景:
* 读取文件一行数据,演示一个传统的流程,如何改造成支持lambda的流程
* @author liangzj5
* @version 1.0
* @date 2021/11/2 13:51
*/
public class ExecuteAround {
private static String filePath = ExecuteAround.class.getClassLoader().getResource("data.txt").getPath();
// 传统实现:固定写死逻辑
public static String processFile() throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(filePath))){
return br.readLine();
}
}
//基于Lambda扩展
//1、行为参数化:
//1.1 引入函数式接口
@FunctionalInterface
interface ProcessFilePredicate{
String process(BufferedReader br) throws IOException ;
}
//1.2 用函数式接口传统行为
public static String processFile(ProcessFilePredicate p) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(filePath))){
return p.process(br);
}
}
public static void main(String[] args) throws IOException {
System.out.println(processFile());
System.out.println("---");
// 基于Lambda的灵活使用
String oneLine = processFile((BufferedReader br) -> br.readLine());
System.out.println(oneLine);
System.out.println("---");
int a=22;
String twoLine = processFile((BufferedReader br) -> a+br.readLine()+br.readLine());
System.out.println(a);
System.out.println(twoLine);
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/liangzj5/JavaStudy.git
git@gitee.com:liangzj5/JavaStudy.git
liangzj5
JavaStudy
JavaStudy
master

搜索帮助