官术网_书友最值得收藏!

Streams

The other major addition to Java 8, and, perhaps where lambdas shine the brightest, is the new Streams API. If you were to search for a definition of Java streams, you would get answers that range from the somewhat circular a stream of data elements to the more technical Java streams are monads, and they're probably both right. The Streams API allows the Java developer to interact with a stream of data elements via a sequence of steps. Even putting it that way isn't as clear as it could be, so let's see what it means by looking at some sample code.

Let's say you have a list of grades for a particular class. You would like to know what the average grade is for the girls in the class. Prior to Java 8, you might have written something like this:

    double sum = 0.0; 
    int count = 0; 
    for (Map.Entry<Student, Integer> g : grades.entrySet()) { 
      if ("F".equals(g.getKey().getGender())) { 
        count++; 
        sum += g.getValue(); 
      } 
    } 
    double avg = sum / count; 

We initialize two variables, one to store the sums and one to count the number of hits. Next, we loop through the grades. If the student's gender is female, we increment our counter and update the sum. When the loop terminates, we then have the information we need to calculate the average. This works, but it's a bit verbose. The new Streams API can help with that:

    double avg = grades.entrySet().stream() 
     .filter(e -> "F".equals(e.getKey().getGender())) // 1 
     .mapToInt(e -> e.getValue()) // 2 
     .average() // 3 
     .getAsDouble(); //4 

This new version is not significantly smaller, but the purpose of the code is much clearer. In the preceding pre-stream code, we have to play computer, parsing the code and teasing out its intended purpose. With streams, we have a clear, declarative means to express application logic. For each entry in the map do the following:

  1. Filter out each entry whose gender is not F.
  2. Map each value to the primitive int.
  3. Average the grades.
  4. Return the value as a double.

With the stream-based and lamba-based approach, we don't need to declare temporary, intermediate variables (grade count and total), and we don't need to worry about calculating the admittedly simple average. The JDK does all of the heavy-lifting for us.

主站蜘蛛池模板: 麟游县| 台东市| 宜良县| 嫩江县| 治县。| 乌什县| 瑞安市| 大英县| 吉木乃县| 阳高县| 资中县| 丁青县| 那曲县| 冀州市| 社旗县| 将乐县| 祁东县| 吉隆县| 富平县| 疏附县| 茂名市| 响水县| 拜城县| 博爱县| 辉南县| 三穗县| 揭阳市| 通辽市| 左贡县| 黄浦区| 抚宁县| 海原县| 林甸县| 光山县| 镇安县| 若羌县| 清徐县| 宝坻区| 满洲里市| 武定县| 铜陵市|