diff --git a/src/main/java/com/teamtreehouse/flashy/services/FlashCardServiceImpl.java b/src/main/java/com/teamtreehouse/flashy/services/FlashCardServiceImpl.java index bb24770..fabbe1a 100644 --- a/src/main/java/com/teamtreehouse/flashy/services/FlashCardServiceImpl.java +++ b/src/main/java/com/teamtreehouse/flashy/services/FlashCardServiceImpl.java @@ -2,15 +2,15 @@ import com.teamtreehouse.flashy.domain.FlashCard; import com.teamtreehouse.flashy.repositories.FlashCardRepository; - +import org.hibernate.mapping.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.*; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.Random; +import java.util.Set; import static java.util.stream.Collectors.toList; @@ -52,21 +52,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; + } + + public 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