-
Notifications
You must be signed in to change notification settings - Fork 304
Expand file tree
/
Copy pathFlashCardServiceImpl.java
More file actions
73 lines (61 loc) · 2.11 KB
/
FlashCardServiceImpl.java
File metadata and controls
73 lines (61 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.teamtreehouse.flashy.services;
import com.teamtreehouse.flashy.domain.FlashCard;
import com.teamtreehouse.flashy.repositories.FlashCardRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import static java.util.stream.Collectors.toList;
@Service
public class FlashCardServiceImpl implements FlashCardService {
private FlashCardRepository flashCardRepository;
@Autowired
public void setFlashCardRepository(FlashCardRepository flashCardRepository) {
this.flashCardRepository = flashCardRepository;
}
@Override
public Long getCurrentCount() {
return flashCardRepository.count();
}
@Override
public FlashCard getFlashCardById(Long id) {
return flashCardRepository.findOne(id);
}
@Override
public FlashCard getNextUnseenFlashCard(Collection<Long> seenIds) {
List<FlashCard> unseen;
if (seenIds.size() > 0) {
unseen = flashCardRepository.findByIdNotIn(seenIds);
} else {
unseen = flashCardRepository.findAll();
}
FlashCard card = null;
if (unseen.size() > 0) {
card = unseen.get(new Random().nextInt(unseen.size()));
}
return card;
}
@Override
public FlashCard getNextFlashCardBasedOnViews(Map<Long, Long> idToViewCounts) {
FlashCard card = getNextUnseenFlashCard(idToViewCounts.keySet());
if (card == null) {
card = getLeastViewedFlashCard(idToViewCounts);
}
return card;
}
public FlashCard getLeastViewedFlashCard(Map<Long, Long> idToViewCounts) {
List<Map.Entry<Long, Long>> 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
public List<FlashCard> getRandomFlashCards(int amount) {
List<FlashCard> cards = flashCardRepository.findAll();
Collections.shuffle(cards);
return cards.stream()
.limit(amount)
.collect(toList());
}
}