Streams

“Talk is cheap. Show me the code.” 

― Linus Torvalds

Map-Filter-Reduce with average() and Optionals

Imagine you have a group of friends that likes to attend a party with you, and you want to find out the average age of those friends. Based on your interactions with your friends, you know that their average age should probably be between 21 (since they can’t drink 😜 ) and 32 (well old geezer 😁 )

You can start by creating a class for your friends

class Friends {
String name;
int age;
double balance;

public Friends(String name, int age) {
this.name = name;
this.age = age;
this.balance = balance;
}
}

We can then simply create a list that stores information about all our friends

List<Friends> friendList = Arrays.asList(
new Friends("John", 25, 406.9),
new Friends("Jean", 30, 200.2),
new Friends("Jake", 15, 300.7),
new Friends("Paul", 20, 140.8),
new Friends("Matt", 19, 900.2)
);

To get the average of friends that are between 21 and 32, we can first stream our friendList data.

friendList.stream()

Since we are only interested in the age portion of our friends’ information, we can simply map each FriendList data to a stream and perform operations on the stream. However, there is a slight challenge, the map() takes a Function whose apply() method. Luckily for us, there is a stream method mapToDouble() that maps the stream object to a primitive.

readings.stream().mapToInt(f -> f.age)

Share your thoughts