Edwin is a software developer, programming languages enthusiast and a novice photographer. Edwin is a DZone MVB and is not an employee of DZone and has posted 12 posts at DZone. You can read more from them at their website. View Full User Profile

Java Streams API Preview

04.11.2013
| 5795 views |
  • submit to reddit

For today’s post I want to share a series of examples that I have developed while trying the latest features in the Java 8 Stream API. In my last post I did a comparison of the features with those available in LINQ, and for today’s post I have decided to go a bit further and try to use the API to work with a small domain model. The examples developed here are based on the same examples presented in the LambdaJ Project.

The Data Model

For the examples I will use the following domain model:

lambda-model

You can see a full implementation of all the examples developed here by downloading the following Gist.

For the examples presented below assume that  in the context of the code there are three streams always available:

  • Stream<Person> persons.
  • Stream<Car> cars.
  • Stream<Sale> sales.

Challenge 1: Print All Car Brands

From a collection of cars print all car brands.

StringJoiner brands = cars.map(Car::getBrand)
.collect(toStringJoiner(","));
String allBrands = brands.toString();

For this example I have also use the new StringJoiner class.

Challenge 2: Select all Sales on Toyota

From a collection of sales, select all those that are related to Toyota cars.

List<Sale> toyotaSales;
toyotaSales = sales.filter(s -> s.getCar().getBrand().equals("Toyota"))
.collect(toList());
toyotaSales.forEach(System.out::println);

For this example I could have also used the forEach method in the stream to get all the sales printed. I did it this way just to illustrate that it is possible to collect all items in the stream into a list and from there we can process them. But ideally, I should have processed the items directly in the stream.

Challenge 3: Find Buys of the Youngest Person

From a collection of sales, find all those that are from the youngest buyer.

ToIntFunction<Entry<Person, List<Sale>>> byAge;
byAge = e -> e.getKey().getAge();
byYoungest = sales.collect(groupingBy(Sale::getBuyer))
.entrySet()
.stream()
.sorted(comparing(byAge))
.map(Entry::getValue)
.findFirst();
if(byYoungest.isPresent()) {
System.out.println(byYoungest.get());
}

Challenge 4: Find Most Costly Sale

From a collection of sales, find the most costly of all of them.

Optional<Sale> mostCostlySale;
Comparator<Sale> byCost = comparing((ToDoubleFunction<Sale>)Sale::getCost)
.reverseOrder();
mostCostlySale = sales.sorted( byCost )
.findFirst();
if(mostCostlySale.isPresent()) {
System.out.println(mostCostlySale.get());
}

Challenge 5: Sum of Sales from Male Buyers & Sellers

From a collection of sales find the sum of all buys/sells made by men.

doublesum = sales.filter(s -> s.getBuyer().isMale()
&& s.getSeller().isMale())
.mapToDouble(Sale::getCost)
.sum();

Challenge 6: Find the Age of the Youngest Buyer

From a collection of sales, find the age of the youngest buyer who bought for more than 40,000.

OptionalInt ageOfYoungest;
ageOfYoungest = sales.filter(sale -> sale.getCost() > 40000)
.map(Sale::getBuyer)
.mapToInt(Person::getAge)
.sorted()
.findFirst();
if(ageOfYoungest.isPresent()) {
System.out.println(ageOfYoungest.getAsInt());
}

Challenge 7: Sort Sales by Cost

Sort a collection of sales by cost.

Comparator<Sale> byCost= comparing((ToDoubleFunction<Sale>) Sale::getCost);
List<Sale> sortedByCost;
sortedByCost = sales.sorted( byCost )
.collect(toList());

Challenge 8: Index Cars by Brand

From a collection of cars, index cars by the their brand.

Map<String,List<Car>> byBrand;
byBrand = cars.collect( groupingBy(Car::getBrand ));

Challenge 9: Find Most Bought Car

From a collection of sales find the most bought car.

ToIntFunction<Entry<Car,List<Sale>>> toSize = (e -> e.getValue().size());
Optional<Car> mostBought;
mostBought = sales.collect( groupingBy(Sale::getCar) )
.entrySet()
.stream()
.sorted( comparing(toSize).reverseOrder() )
.map(Entry::getKey)
.findFirst();
if(mostBought.isPresent()) {
System.out.println(mostBought.get());
}

Related Posts

Futher Reading

Published at DZone with permission of Edwin Dalorzo, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)