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