Merging denormalized data into a relational structure

44 views Asked by At

Let's say we have an entity Foo which comes from a denormalized DB table. And let's say it looks like this:

record Foo(int id, String discriminator, String value, String otherValue)

and we want to convert that to a relational structure which would look like this

Bar(
  String discriminator,
  List<Baz> bazList
)

Baz(
  String value,
  String otherValue
)

How could I elegantly accomplish something like that in java? The only thing that comes to mind is simply iterating over Foo convert and store the values in a map (so if a Bar instance already exists, add to it, if it doesn't create it). I am wondering if there is a way to do this without creating a map though

1

There are 1 answers

0
shmosel On BEST ANSWER

I think you'll need the intermediate map, but you can streamline it with streams:

List<Bar> result = foos.stream()
        .collect(groupingBy(foo::discriminator,
                mapping(f -> new Baz(f.value(), f.otherValue()), toList())))
        .entrySet()
        .stream()
        .map(e -> new Bar(e.getKey(), e.getValue()))
        .toList();