Simple Streams Tutorial

From Progzoo
Jump to: navigation, search

Introducing Streams - you can practice using the operations count() and sum() on a simple stream of integers.

You will also use min() and max() together with getAsInt().

You can use skip(n) and limit(n) to extract parts of the stream.

Count and Sum

count and sum are reduction operators - they take a list of values and reduce them to a single value.

  • mths is a list giving the number of days in each month
  • the program shown gives the number of items in the list.

Change the program so that it shows the total.

[Font] [Default] [Show] [Resize] [History] [Profile]

Shortest Month

Operations like max and min might not give a value (if the list is empty). The OptionalInt type might be None. You can convert an OptionalInt to a normal int using getAsInt()

Show the number of days in the shortest month.

[Font] [Default] [Show] [Resize] [History] [Profile]

Average Month

Show the average number of days in a month.

You will need to:

  • declare x as a double not an int
  • use the operation average
  • convert the OptionalDouble to double using getAsDouble()

[Font] [Default] [Show] [Resize] [History] [Profile]

First Month

How many days in the first month?

You can use findFirst() to get the first item - it will be an OptionalInt

[Font] [Default] [Show] [Resize] [History] [Profile]

First Three Months

How many days in the first three months?

You can use limit(3) to extract just the first three items.

[Font] [Default] [Show] [Resize] [History] [Profile]

Last six months

How many days, excluding the first 6 months?

You can use skip(6) to remove first 6 items.

[Font] [Default] [Show] [Resize] [History] [Profile]