I'm starting using java 8 stream API. I would like to convert a list of "sql result set" to domain objects, i.e composite structure.
Domain objects : a user has a collection of permissions, each permission has a collection of year of applications. For example, John has 2 permissions (MODERATOR and DEV). its moderator permission is only applicable for 2014 and 2015 its dev permission of only applicable for 2014.
class User {
// some primitives attributes
List<Permission> permission;
}
class Permission {
// some primitives attributes
List<Integer> years;
}
Now I make a query and got a list of flat results, something like:
[1, "moderator", 2014]
[1, "moderator", 2015]
[1, "dev", 2014]
[2, "dev", 2010]
[2, "dev", 2011]
[2, "dev", 2012]
The 1 and 2 are userId.
I tried various construction but at the end it's more complex than fluent. And didn't work :)
I read in a Java 8 book that it's "simple" to build dompain objects with collectors.
I cried a little when I read that :'(
I tried
sb.collect(
collectingAndThen(
groupingBy(
Mybean::getUserId,
collectingAndThen(
groupingBy(Monbean::getPermissionId, mapping(convertPermission, toList())),
finisherFonction)
),
convertUser)
);
and got one hell of generics compilation failure.
- what's the best way to construct multi level composite domain objects using java 8 streams ?
- is collectionAndThen / finisher a good idea?
- or do you use only groupingBy followed by a mapping function?
- do you transform the classifier to an object (sort of first level mapping function?)
Because at the end I want to get rid of the Map and got a List<User> result (I think I can add a map call on the entrySet to finish the transformation).