国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

利用JDK8的新特性計算某個目錄下的文件中包含字符串的次數

2019-11-11 06:40:10
字體:
來源:轉載
供稿:網友
需求:計算某個字符串在某個文件夾中出現的次數。**這篇文章利用了JDK1.8的新特性Stream流和Lambda表達式并結合了線程池的使用。**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 { //創建5個固定線程的線程池 ExecutorService executorService = Executors.newFixedThreadPool(5); List<Future<Pair<String, Integer>>> listFile = //這里是取所傳入目錄的最多四層,如果不知道這個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>>) () -> {//創建N多個Callable實現類 Pair<String, Integer> pair = null;//這里的鍵值對用pair比用Map更好一些 try { Optional optional = Files.lines(file).map(str -> { int count = 0; int index = str.indexOf("main"); if (index >= 0) { //這里需要循環計算,因為可能在某一行中會出現多次 do { count++; } while ((index = str.indexOf("main", index + 1)) > 0); } return count; }).reduce(Integer::sum);//合并最終的計算結果 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))//提交給線程池進行處理 .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次出現在%s文件中", file.getValue(), file.getKey()))); //關閉線程池 executorService.shutdown(); } catch (Exception e) { e.printStackTrace(); } } public void test() { String str = "mainmainmainmainmain"; }}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 库车县| 兴文县| 沂南县| 通山县| 冕宁县| 西峡县| 扶绥县| 杭锦后旗| 瑞安市| 宁陕县| 天镇县| 和林格尔县| 丹巴县| 桃园县| 临洮县| 康定县| 运城市| 昭平县| 沭阳县| 商都县| 宁夏| 张北县| 溧水县| 高陵县| 富裕县| 泌阳县| 广安市| 汝南县| 富顺县| 东莞市| 莱芜市| 乐陵市| 九龙县| 沈阳市| 甘谷县| 察隅县| 鹿泉市| 仪征市| 淮北市| 松滋市| 徐闻县|