如何转换此代码以使用lambda和stream api

时间:2017-03-29 07:22:09

标签: java

我们如何在这种情况下使用lambda和stream api

Map<String, Integer> map = new LinkedHashMap<>();
BufferedReader br = new BufferedReader(new FileReader(new File(("test.txt"))));
String line = ""; String[] words;
while((line = br.readLine()) != null){
    words = line.split(" ");
    for(String word : words){
        if(map.containsKey(word)){
            map.put(word, map.get(word)+1);
        }else{
             map.put(word, 1);
        }
    }
}
System.out.println(map);

2 个答案:

答案 0 :(得分:2)

您可以参考以bufferedReader.stream()开头的以下代码,并按照内联评论进行操作:

Map<String, Integer> map = new LinkedHashMap<>();
BufferedReader br = new BufferedReader(new FileReader(new File(("test.txt"))));

br.lines()//get stream from BufferedReader
  .map(line -> line.split(" "))//split lines to array
  .flatMap(stream -> Arrays.stream(stream))//convert array to stream
  .collect(Collectors.toMap( s -> s, s -> 1,Integer::sum ));//collect stream to Map

答案 1 :(得分:0)

如果我正确理解您的代码,您只是计算文件中单个单词的出现次数。如果这是正确的:

Map<String, Long> wordCount = br.lines()
    .flatMap(l -> Arrays.stream(l.split(" "))
    .collect(groupingBy(w -> w, counting());