Skip to content

Instantly share code, notes, and snippets.

@joaomantovani
Created May 16, 2019 17:30
Show Gist options
  • Save joaomantovani/d07398fcf56fee883bc5b4bf437540a5 to your computer and use it in GitHub Desktop.
Save joaomantovani/d07398fcf56fee883bc5b4bf437540a5 to your computer and use it in GitHub Desktop.
getBestSellers
public List<Book> getBestSellers(String subject) throws BestSellersNotFoundException {
Map<Book, Integer> map = new HashMap<Book, Integer>();
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -1);
Date date = calendar.getTime();
for (Order order: ordersById) {
if (order.getDate().compareTo(date) > 0) {
for (OrderLine orderLine: order.getLines()) {
int qtdy = 0;
if (subject.equalsIgnoreCase(orderLine.getBook().getSubject())) {
if (map.get(orderLine.getBook()) != null) {
qtdy = map.get(orderLine.getBook());
}
map.put(orderLine.getBook(), orderLine.getQty() + qtdy);
}
}
}
}
// now let's sort the map in decreasing order of value
List<Book> arr = new ArrayList<Book>();
if (map.size() == 0) {
throw new BestSellersNotFoundException("Quantidade de livros é 0");
}
Map<Book, Integer> sorted = map
.entrySet()
.stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.collect(
Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
LinkedHashMap::new));
arr = new ArrayList<Book>(map.keySet());
return arr.subList(0, arr.size() >= 50 ? 50 : arr.size());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment