java用法總結
- 計時
long startTime = System.nanoTime();
solution.process(inputFile);
long endTime = System.nanoTime();
long totalTime = (endTime - startTime) / 1000; // 單位 us
- 按行讀文件
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(inputPath)), "UTF-8"));
String lineTxt;
while ((lineTxt = br.readLine()) != null) {
// do something
}
- 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
}
- 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();
}
- Set使用
Set<String> s = new HashSet<>();
// 添加元素
s.add(id1);
// 判斷是否存在key
boolean b = s.contains(key);
- String與Integer轉換
// String轉Integer
Integer i = Integer.valueOf("123");
// Integer轉String
String s = String.valueOf(123);
- 數組
int mapSize = 2000000;
int[] map = new int[mapSize];
map[0] = 100;
int i1 = map[0];
加速點
- 切分字符串「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];
- 提早分配空間
// 較快
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<>();
- 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.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];
}