需求:計(jì)算某個(gè)字符串在某個(gè)文件夾中出現(xiàn)的次數(shù)。**這篇文章利用了JDK1.8的新特性Stream流和Lambda表達(dá)式并結(jié)合了線程池的使用锉罐。**
package com.zkn.fullstacktraining.seventh;
import javafx.util.Pair;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.*;
import java.util.stream.Collectors;
/**
* Created by zkn on 2017/2/5.
*/
public class SearchStringByThreadPool {
public static void main(String[] args) {
try {
//創(chuàng)建5個(gè)固定線程的線程池
ExecutorService executorService = Executors.newFixedThreadPool(5);
List<Future<Pair<String, Integer>>> listFile =
//這里是取所傳入目錄的最多四層号涯,如果不知道這個(gè)API的話需要遞歸去做。
Files.walk(Paths.get("D:\\CUST\\workspace\\JavaCore\\FullStackTraining\\src\\main\\java\\com\\zkn"), 4)
.filter(file -> !Files.isDirectory(file) && file.toString().endsWith("java"))//文件文件夾和不是java的文件
.map(file -> (Callable<Pair<String, Integer>>) () -> {//創(chuàng)建N多個(gè)Callable實(shí)現(xiàn)類
Pair<String, Integer> pair = null;//這里的鍵值對(duì)用pair比用Map更好一些
try {
Optional optional = Files.lines(file).map(str -> {
int count = 0;
int index = str.indexOf("main");
if (index >= 0) {
//這里需要循環(huán)計(jì)算青扔,因?yàn)榭赡茉谀骋恍兄袝?huì)出現(xiàn)多次
do {
count++;
} while ((index = str.indexOf("main", index + 1)) > 0);
}
return count;
}).reduce(Integer::sum);//合并最終的計(jì)算結(jié)果
int count = optional.isPresent() ? (int) optional.get() :0;
pair = new Pair<>(file.toString(),count);
} catch (IOException e) {
e.printStackTrace();
}
return pair == null ? new Pair<>("", 0) : pair;
})
.map(file -> executorService.submit(file))//提交給線程池進(jìn)行處理
.collect(Collectors.toList());
listFile.stream().map(file -> {
Pair<String, Integer> pair = null;
try {
pair = file.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return pair == null ? new Pair<>("", 0) : pair;
})
.filter(file -> file.getValue() > 0)//過濾掉不包含字符串的文件
.sorted((s1, s2) -> Integer.compare(s2.getValue(), s1.getValue()))//從大到小排序
.forEach(file -> System.out.println(String.format("%d次出現(xiàn)在%s文件中", file.getValue(), file.getKey())));
//關(guān)閉線程池
executorService.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
public void test() {
String str = "mainmainmainmainmain";
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者