用lambd怎么使用呢
时间: 2023-07-08 11:46:20 浏览: 134
使用Lambda表达式可以简化Java代码,并且可以使代码更加易读和易于维护。下面以Java 8为例,演示如何使用Lambda表达式查询菜单树表:
```java
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class MenuTree {
public static void main(String[] args) {
try {
// 连接数据库
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
// 执行查询语句,并使用Lambda表达式对ResultSet进行处理
List<Menu> menus = new ArrayList<>();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, ParentId, delectableflag FROM menu");
while (rs.next()) {
Menu menu = new Menu(
rs.getInt("id"),
rs.getString("name"),
rs.getInt("ParentId"),
rs.getBoolean("delectableflag")
);
menus.add(menu);
}
// 关闭连接
rs.close();
stmt.close();
conn.close();
// 根据菜单项构建菜单树,使用Lambda表达式进行递归
List<Menu> menuTree = buildMenuTree(menus, 0);
menuTree.forEach(Menu::print);
} catch (Exception e) {
e.printStackTrace();
}
}
private static List<Menu> buildMenuTree(List<Menu> menus, int parentId) {
List<Menu> result = new ArrayList<>();
menus.stream()
.filter(menu -> menu.getParentId() == parentId)
.forEach(menu -> {
List<Menu> children = buildMenuTree(menus, menu.getId());
menu.setChildren(children);
result.add(menu);
});
return result;
}
}
class Menu {
private int id;
private String name;
private int parentId;
private boolean delectableflag;
private List<Menu> children;
public Menu(int id, String name, int parentId, boolean delectableflag) {
this.id = id;
this.name = name;
this.parentId = parentId;
this.delectableflag = delectableflag;
}
public int getId() { return id; }
public String getName() { return name; }
public int getParentId() { return parentId; }
public boolean isDelectable() { return delectableflag; }
public List<Menu> getChildren() { return children; }
public void setChildren(List<Menu> children) { this.children = children; }
public void print() {
print(0);
}
private void print(int level) {
System.out.println(String.format("%s%s (%d)", " ".repeat(level * 2), name, id));
if (children != null) {
for (Menu child : children) {
child.print(level + 1);
}
}
}
}
```
以上代码中,使用Lambda表达式对ResultSet进行处理,将每个菜单项构建成Menu对象,并将它们添加到列表中。然后,使用Lambda表达式对列表进行递归,根据每个菜单项的parentId构建菜单树。最后,使用Lambda表达式输出菜单树。
阅读全文