From 964037816e7e129be62b27cbedcbf20bc5af71d5 Mon Sep 17 00:00:00 2001 From: joelramsey Date: Sat, 15 May 2021 14:58:50 +0200 Subject: [PATCH] Conducted code refactor within the FC service impl to ensure that the style aligns with previous class patterns --- .idea/encodings.xml | 6 ++++ .../flashy/services/FlashCardServiceImpl.java | 31 ++++++++----------- 2 files changed, 19 insertions(+), 18 deletions(-) create mode 100644 .idea/encodings.xml diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..97626ba --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/src/main/java/com/teamtreehouse/flashy/services/FlashCardServiceImpl.java b/src/main/java/com/teamtreehouse/flashy/services/FlashCardServiceImpl.java index bb24770..92ce4df 100644 --- a/src/main/java/com/teamtreehouse/flashy/services/FlashCardServiceImpl.java +++ b/src/main/java/com/teamtreehouse/flashy/services/FlashCardServiceImpl.java @@ -6,11 +6,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Random; +import java.util.*; import static java.util.stream.Collectors.toList; @@ -52,21 +48,20 @@ public FlashCard getNextUnseenFlashCard(Collection seenIds) { @Override public FlashCard getNextFlashCardBasedOnViews(Map idToViewCounts) { FlashCard card = getNextUnseenFlashCard(idToViewCounts.keySet()); - if (card != null) { - return card; + if (card == null) { + card = getLeastViewedFlashCard(idToViewCounts); } + return card; + } + + private FlashCard getLeastViewedFlashCard(Map idToViewCounts) { Long leastViewedId = null; - for (Map.Entry entry : idToViewCounts.entrySet()) { - if (leastViewedId == null) { - leastViewedId = entry.getKey(); - continue; - } - Long lowestScore = idToViewCounts.get(leastViewedId); - if (entry.getValue() < lowestScore) { - leastViewedId = entry.getKey(); - } - } - return flashCardRepository.findOne(leastViewedId); + List> entries = new ArrayList<>(idToViewCounts.entrySet()); + Collections.shuffle(entries); + return entries.stream() + .min(Comparator.comparing(Map.Entry::getValue)) + .map(entry -> flashCardRepository.findOne(entry.getKey())) + .orElseThrow(IllegalArgumentException::new); } @Override