Java 8 Streams and Collectors - Magical GroupBy features like SQL
Hi All,
Sorry, I was away for a long period of time. But, I learned something yesterday and couldn't resist myself from sharing it here. You may already be aware about it, but I am lagging behind and still using Java 7 on my projects....
In past, I have always ended up using SQL to perform any GroupBy or other complex transformations because - firstly, they are easy to write and secondly, they are efficient. But, I learnt this new java feature which is introduced in Java 8 and I was so amazed.
My task was to group by 2 fields(country and credit_rating) in a collection and then calculate the average of third field (amount). If country is unavailable for any record, then I had to use city field instead. [Note: There were other conditions, but let's keep this example simple here]
companyList.stream().collect( Collectors.groupingBy( p -> (p.getCountry() == null)? p.getCity() : p.getCountry(), Collectors.groupingBy(p -> p.getCreditRating().toUpperCase(), Collectors.averagingDouble( p -> p.getAmount()))));
What, just one line?? .. as we might have done in SQL. Isn't it amazing? With Java 7, this would have taken lot of lines of code. Not just "GroupBy" for say, using Stream and Collectors util classes, we can now perform all types of complex transformation and conversions.
I have to hurry up and learn other features of Java 8 quickly, because Java 9 is knocking at the door :-)
PS - This post was published on my official blog page on Nov 16 2017. Java 9 is already released now!!
Comments
Post a Comment