1、递归深渊(获取数结构)
public static void main(String[] args) {
ThreadTest threadTest = new ThreadTest();
System.out.println(threadTest.getName());
List<Node> nodes = new ArrayList<>();
nodes.add(new Node(1,0,"root-0-1"));
nodes.add(new Node(2,0,"root-0-2"));
nodes.add(new Node(3,1,"leaf-1-3"));
nodes.add(new Node(4,2,"leaf-2-4"));
nodes.add(new Node(5,1,"leaf-1-5"));
nodes.add(new Node(6,4,"leaf-4-6"));
nodes.add(new Node(7,3,"leaf-3-7"));
nodes.add(new Node(8,1,"leaf-1-6"));
List<Node> roots = nodes.stream().filter(item -> Objects.equals(item.getParentId(), 0)).collect(Collectors.toList());
Map<Node, Object> map = nodesMapping(roots, nodes);
printTree(map,"");
}
public static void printTree(Map<Node, Object> map,String format) {
format = "***" + format ;
for (Map.Entry<Node, Object> entry : map.entrySet()) {
System.out.println(format + entry.getKey().getName());
if (entry.getValue() instanceof Map) {
if (((Map) entry.getValue()).size() > 0) {
printTree((Map)entry.getValue(),format );
}
}
}
}
public static Map<Node,Object> nodesMapping(List<Node> roots,List<Node> nodes) {
Map<Node,Object> map = new HashMap<>();
//获取所有节点 可以作为 父节点的节点
Set<Integer> collect3 = nodes.stream().map(item -> item.getParentId()).collect(Collectors.toSet());
for (Node root : roots) {
HashMap<Node,Object> leaf = new HashMap<>();
//找到当前以当前节点为父节点的 所有子节点
List<Node> collect = nodes.stream().filter(item -> root.getId().equals(item.getParentId())).collect(Collectors.toList());
//找到 子节点 有子孙节点的节点
List<Node> collect1 = collect.stream().filter(item -> collect3.contains(item.getId())).collect(Collectors.toList());
//找到 子节点 没有子孙节点的节点
List<Node> collect2 = collect.stream().filter(item -> !collect3.contains(item.getId())).collect(Collectors.toList());
// 递归获取字节点 下的所有子孙节点
Map<Node, Object> nodeObjectMap = nodesMapping(collect1, nodes);
// 如果没有子孙节点 用空map作标志
collect2.forEach(item->{
leaf.put(item,new HashMap<>());
});
// 有子孙节点 获取子孙节点
nodeObjectMap.forEach((item,value)->{
leaf.put(item, value);
});
map.put(root,leaf);
}
return map;
}
输出结果
***root-0-1 ******leaf-1-6 ******leaf-1-5 ******leaf-1-3 *********leaf-3-7 ***root-0-2 ******leaf-2-4 *********leaf-4-6
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
class Solution {
public int lengthOfLongestSubstring(String s) {
int max = 0;
int curNoStrIndexStart = 0;
Map<String,Integer> map = new HashMap<>();
for (int i=0;i < s.length();i++) {
String index = String.valueOf(s.charAt(i));
if (map.containsKey(index)) {
curNoStrIndexStart = Math.max(map.get(index),curNoStrIndexStart);
}
max = Math.max(max,i - curNoStrIndexStart +1);
map.put(index,i + 1);
}
return max;
}
}
2、mysql获取表的元数据信息
import java.io.*;
import java.sql.*;
import java.util.*;
public class DBEntityInit {
private static String propName = "db.properties";
private static Connection connection = null;
private static Map<String, List<Column>> tableData = new HashMap<>();
static {
connection = getConnection(propName);
}
public static Connection getConnection(String propName){
Connection conn = null;
try {
InputStream in = new FileInputStream(new File(propName));
Properties properties = new Properties();
properties.load(in);
String url = properties.getProperty("jdbc.url");
String username = properties.getProperty("jdbc.username");
String driver = properties.getProperty("jdbc.driver");
String password = properties.getProperty("jdbc.password");
Class.forName(driver);
conn = DriverManager.getConnection(url,username,password);
} catch (SQLException | ClassNotFoundException | IOException e) {
e.printStackTrace();
}
return conn;
}
public static void initTableData() {
ResultSet tables = null;
try {
DatabaseMetaData metaData = connection.getMetaData();
tables = metaData.getTables(null, null, null, new String[]{"TABLE"});
while (tables.next()) {
tableData.put(tables.getString(3),new ArrayList<>());
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (tables != null) {
tables.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void initTableColumn(String tableName) {
List<Column> columns = tableData.get(tableName);
PreparedStatement pst = null;
try {
String sql = "select * from " + tableName;
pst = connection.prepareStatement(sql);
ResultSetMetaData metaData = pst.getMetaData();
int columnCount = metaData.getColumnCount();
for (int i=0 ; i < columnCount; i++) {
Column column = new Column();
column.setName(metaData.getColumnName(i+1));
column.setType(metaData.getColumnTypeName(i+1));
columns.add(column);
}
//tableData.put(tableName,columns);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (pst != null) {
pst.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void initComment(String tableName) {
//与数据库的连接
PreparedStatement pst = null;
String tableSql = "select * from" + tableName;
List<String> comments = new ArrayList<>();//列名注释集合
ResultSet rs = null;
List<Column> columns = tableData.get(tableName);
try {
pst = connection.prepareStatement(tableSql);
rs = pst.executeQuery("show full columns from " + tableName);
while (rs.next()) {
String comment = rs.getString("Comment");
comments.add(comment);
}
for (int i=0 ;i < columns.size() ;i++) {
Column column = columns.get(i);
column.setComment(comments.get(i));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void closeConnection(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static Map<String, List<Column>> init() {
initTableData();
for (String key : tableData.keySet()) {
initTableColumn(key);
initComment(key);
}
closeConnection(connection);
return tableData;
}
public static String getPropName() {
return propName;
}
public static void setPropName(String propName) {
DBEntityInit.propName = propName;
}
public static void main(String[] args) {
init();
for (Map.Entry<String,List<Column>> entry : tableData.entrySet()) {
List<Column> value = entry.getValue();
System.out.println("--------------表名" + entry.getKey());
for (Column column : value) {
System.out.print(column.getName() + "---");
System.out.print(column.getType() + "---");
System.out.print(column.getComment());
System.out.println();
}
}
}
// public static void initColumnComment(String tableName) {
//
// try {
// List<Column> cList = tableData.get(tableName);
// DatabaseMetaData metaData = connection.getMetaData();
// ResultSet columns = metaData.getColumns(null, null, tableName, "%");
//
// while (columns.next()) {
// Column column = new Column();
// String name = columns.getString("COLUMN_NAME");
// String type = columns.getString("TYPE_NAME");
// String comment = columns.getString("REMARKS");
// column.setName(name);
// column.setType(type);
// column.setComment(comment);
// cList.add(column);
// }
// } catch (SQLException e) {
// e.printStackTrace();
// }
//
// }
}
相关实体
public class Column {
private String name;
private String type;
private String comment;
public String getName() {
return name;
}
public void setName(String name) {
name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
3.日期操作
3、日期的加减操作
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateCalculate {
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* 获取形如yyyy-MM-dd HH:mm:ss
* @param date
* @return
*/
public static String datetimeToString(Date date) {
return sdf.format(date);
}
/**
* 根据时间字符串获取日期
* @param dateString
* @return
* @throws ParseException
*/
public static Date stringToDatetime(String dateString) throws ParseException {
return sdf.parse(dateString);
}
/**
* 获取本月最后一天
* @return
*/
public static Date getMonthStartDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_MONTH,1);
return calendar.getTime();
}
/**
* 获取本月最后一天
* @return
*/
public static Date getMonthEndDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
return calendar.getTime();
}
/**
* 获取指定日期所属周的开始时间
* @param date
* @return
*/
public static Date getBeginWeekDate(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == 1) {
dayOfWeek += 7;
}
cal.add(Calendar.DATE,2 - dayOfWeek);
return cal.getTime();
}
/**
* 距离指定日期所属周结束时间
* @return
*/
public static Date getEndWeekDate(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == 1) {
dayOfWeek += 7;
}
cal.add(Calendar.DATE,8 - dayOfWeek);
return cal.getTime();
}
/**
* 对指定日期进行年份加减操作
* @param date
* @param num
* @return
*/
public static Date calculateDateOfYear(Date date,Integer num) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.YEAR,num);
return calendar.getTime();
}
/**
* 对指定日期月份进行加减操作
* @param date
* @param num
* @return
*/
public static Date calculateDateOfMonth(Date date,Integer num) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH,num);
return calendar.getTime();
}
/**
* 对指定日期天数进行加减操作
* @param date
* @param num 负整数 正整数
* @return
*/
public static Date calculateDateOfDay(Date date,Integer num) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH,num);
return calendar.getTime();
}
public static void main(String[] args) throws ParseException {
System.out.println(datetimeToString(getMonthStartDate(sdf.parse("2019-12-04 12:09:52"))));
System.out.println(datetimeToString(getEndWeekDate(sdf.parse("2019-12-04 12:09:52"))));
System.out.println(datetimeToString(calculateDateOfYear(stringToDatetime("2019-12-04 12:09:52"),-2)));
}
}
3.反射
public static void vaildate() throws Exception {
Node node = new Node(1, 0, "节点1");
Class<? extends Node> clazz = node.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
Nullable annotation = field.getAnnotation(Nullable.class);
boolean flag = annotation.flag();
//如果不为空
if (!flag) {
Class<?> type = field.getType();
if(type.equals(Long.class)) {
Long l = (Long) field.get(node);
if (l == null) {
throw new Exception("参数不能为空");
}
}
if(type.equals(String.class)) {
String s = (String) field.get(node);
if (s == null || Objects.equals("",s)) {
throw new Exception("参数不能为空");
}
}
if(type.equals(Integer.class)) {
Integer i = (Integer) field.get(node);
if (i == null) {
throw new Exception("参数不能为空");
}
}
if(type.equals(Double.class)) {
Double d = (Double) field.get(node);
if (d == null) {
throw new Exception("参数不能为空");
}
}
}
}
}
public static Node setValue() throws IllegalAccessException, InstantiationException {
//准备数据
Map<String,Object> map = new HashMap<>();
map.put("id",1);
map.put("parentId",1);
map.put("name","节点1");
//获取属性
Class<Node> clazz = Node.class;
Node node = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
//私有属性设置值
field.setAccessible(true);
field.set(node,map.get(field.getName()));
}
System.out.println("id: " +node.getId() + " parentId: " + node.getParentId() + " name: " + node.getName());
return node;
}
实体与注解
public class Node {
@Nullable(flag = false)
private Integer id;
@Nullable(flag = false)
private Integer parentId;
@Nullable(flag = true)
private String name;
public Node() {
}
public Node(Integer id, Integer parentId, String name) {
this.id = id;
this.parentId = parentId;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author zzm @Date 2020/7/6
**/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Nullable {
boolean flag();
}