Praveen Praveen - 1 year ago 37
Java Question

Can we combine Two POJO from two Json to one

I am not a 100% on how to do this yet . But I will explain the situation first.

I am letting a user search for book and give 10 recommendations based on the first result in search . I store the recommended Books in

once I have the recommended books I am getting the review on each book storing in another POJO

Intention : Now I want to show the recommeded book based on the review

I am kind of stuck on how to sort the reviews and not basically create a copy of RecommendedBooks that is orderd based on review.

Anyone has any good way of doing this?

Answer Source

Take these classes:

class Book {
  String id;
  String name;

class Review {
  String bookId;
  String text;

class QueryResult {
  Book book;
  Review review;

First you get 10 recommended Books:

List<Book> recommended = queryFor10RecommendedBooks();

Then get the reviews and wrap everything in List<QueryResult>:

List<QueryResult> result =
  .map(b -> new QueryResult(book, getReviewForBook(b)))

This code will query one Review at a time. You can also optimize it to query all reviews for all 10 Books, and then afterwards put them together. Depends on your data structure / database what is faster.

Other nice way would be to have a result as Map<Book, Review> which is simple as well:

Map<Book, Review> result =
  .collect(Collectors.toMap(Function.identity(), b -> getReviewForBook(b)));