【java】java基本用法记录

时间:2024-01-17 12:46:02

java用法总结

  1. 计时
long startTime = System.nanoTime();
solution.process(inputFile);
long endTime = System.nanoTime();
long totalTime = (endTime - startTime) / 1000; // 单位 us
  1. 按行读文件
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(inputPath)), "UTF-8"));
String lineTxt;
while ((lineTxt = br.readLine()) != null) {
// do something
}
  1. List使用
List<List<String>> res = new ArrayList<>();

// 添加元素
List<String> tmp = new ArrayList<>();
tmp.add("1");
tmp.add("2");
res.add(tmp); // 获取指定位置元素
res.get(1); // 获取长度
Integer len = res.size(); // 遍历
for (List<String> r : res) {
// do something
}
  1. Map使用
Map<String, Integer> m = new HashMap<>();

// 插入
m.put(id1, newIndex); // 取出
Integer index1 = m.get(id1); // 如果不存在key则会返回null // 判断是否存在key
if (id2index.containsKey()){
// do something
} // 遍历
for(Map.Entry<String, Integer> entry: m.entrySet()){
String key = entry.getKey();
Integer value = entry.getValue();
}
  1. Set使用
Set<String> s = new HashSet<>();

// 添加元素
s.add(id1); // 判断是否存在key
boolean b = s.contains(key);
  1. String与Integer转换
// String转Integer
Integer i = Integer.valueOf("123"); // Integer转String
String s = String.valueOf(123);
  1. 数组
int mapSize = 2000000;
int[] map = new int[mapSize];
map[0] = 100;
int i1 = map[0];

加速点

  1. 切分字符串“0001A,0001B”
// 速度较快, 百万量级下速度加快1s
String id1 = lineTxt.substring(0, 5);
String id2 = lineTxt.substring(6); // 速度较慢
String[] twoId = ids.split(",");
String id1 = twoId[0];
String id2 = twoId[1];
  1. 提前分配空间
// 较快
Map<String, Integer> id2index = new HashMap<>(1500000);
List<List<String>> res = new ArrayList<>(1500000); // 较慢
Map<String, Integer> id2index = new HashMap<>();
List<List<String>> res = new ArrayList<>();
  1. Map取值直接取,不必先判断是否存在key
// 较快
Integer index1 = id2index.get(id1);
Integer index2 = id2index.get(id2);
if (index1 != null && index2 != null){} // 较慢
if (id2index.containsKey(id1) && id2index.containsKey(id2)){
Integer index1 = id2index.get(id1);
Integer index2 = id2index.get(id2);
}
  1. 读文件用字节读取 百万量级可从1.5s加速到0.4s左右
FileInputStream is;
static int bufferSize = 65536;
static byte buffer[] = new byte[bufferSize];
int pos = bufferSize; is = new FileInputStream(inputPath);
while(true) {
bufferSize = is.read(buffer, 0, bufferSize);
if(bufferSize == -1) {
return -1; //读完了
}
char c = (char) buffer[0];
}