java8 Stream的應用
阿新 • • 發佈:2018-12-03
統計所有單詞的總個數和每個單詞出現的次數
使用了檔案流,中間操作有常用的map,flatmap,filter,groupingby等。
Java8 的Stream的簡單應用
1.txt 檔案
hello world
hello java
hello tom
hello lucy
lucy java
lucy tom
@Test public void getCountNum(){ try { BufferedReader br = new BufferedReader(new FileReader("../1.txt")); int sum = br.lines().map(String::trim) .filter(s -> !s.isEmpty()) .map(s -> s.split(" ")) .mapToInt(array -> array.length) .parallel() .sum(); System.out.println(sum); }catch (Exception e){ } } @Test public void getWordCount(){ try { BufferedReader br = new BufferedReader(new FileReader("../1.txt")); Map<String, Long> collect = br.lines().map(String::trim) .filter(s -> !s.isEmpty()) .map(s -> s.split(" ")) .map(array -> Stream.of(array)) .flatMap(s -> s) .collect(Collectors.groupingBy(s -> s, Collectors.counting())); System.out.println(collect); Iterator<Map.Entry<String, Long>> iterator = collect.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, Long> next = iterator.next(); System.out.println(next.getKey() + "====" + next.getValue()); } }catch (Exception e){ } }