Posts

Showing posts from 2018

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  -...