How to get words average length using Lambda Expression

后端 未结 3 1341
终归单人心
终归单人心 2021-01-04 17:24

I have a word list text file, I want to get min, max and average word lengths from that file.

I have a stream method:

public static Stream

        
相关标签:
3条回答
  • 2021-01-04 17:26

    The lines() method will get you a stream of the lines, not the words. Once you have the Stream, call flatMap to replace the lines with the words, supplying the lambda expression to split out the words:

    Stream<String> stringStream = reader.lines().flatMap( line -> 
        Stream.of(line.split("\\s+"))
    );
    

    This will correct your implementation of max and min. It also affects the correctness of any average calculation you wish to implement.

    To obtain the average, you can call mapToInt to map the stream of words to their lengths (yielding an IntStream), then call average, which returns an OptionalDouble.

    System.out.println(readWords(filename)
        .mapToInt( s -> s.length() )  // or .mapToInt(String::length)
        .average()
        .getAsDouble());
    
    0 讨论(0)
  • 2021-01-04 17:38

    Use IntSummaryStatistics to get the min, max and average in one pass.

    IntSummaryStatistics summary = readWords(filename)
        .collect(Collectors.summarizingInt(String::length));
    System.out.format("min = %d, max = %d, average = %.2f%n",
        summary.getMin(), summary.getMax(), summary.getAverage());
    
    0 讨论(0)
  • 2021-01-04 17:45

    Based on official documentation about reductions

    System.out.println(readWords(filename)
                    .mapToInt(String::length)
                    .average()
                    .getAsDouble()
    );
    

    Note that you can and probably should use method references like String::length

    0 讨论(0)
提交回复
热议问题