• 9.5.3 集合(Collection)类型的使用范例

    9.5.3 集合(Collection)类型的使用范例

    Redisson提供的RSetRSetCacheRListRSortedSetRScoredSortedSetRQueueRBlockingQueueRDequeRBlockingDequeRPriorityQueueRPriorityDeque这几种集合(Collection)类型的对象均可以使用这种分布式映射归纳(MapReduce)服务。

    以下是在集合(Collection)类型的基础上采用映射归纳(MapReduce)来实现字数统计的范例:

    1. public class WordMapper implements RCollectionMapper<String, String, Integer> {
    2. @Override
    3. public void map(String value, RCollector<String, Integer> collector) {
    4. String[] words = value.split("[^a-zA-Z]");
    5. for (String word : words) {
    6. collector.emit(word, 1);
    7. }
    8. }
    9. }
    1. public class WordReducer implements RReducer<String, Integer> {
    2. @Override
    3. public Integer reduce(String reducedKey, Iterator<Integer> iter) {
    4. int sum = 0;
    5. while (iter.hasNext()) {
    6. Integer i = (Integer) iter.next();
    7. sum += i;
    8. }
    9. return sum;
    10. }
    11. }
    1. public class WordCollator implements RCollator<String, Integer, Integer> {
    2. @Override
    3. public Integer collate(Map<String, Integer> resultMap) {
    4. int result = 0;
    5. for (Integer count : resultMap.values()) {
    6. result += count;
    7. }
    8. return result;
    9. }
    10. }
    1. RList<String> list = redisson.getList("myList");
    2. list.add("Alice was beginning to get very tired");
    3. list.add("of sitting by her sister on the bank and");
    4. list.add("of having nothing to do once or twice she");
    5. list.add("had peeped into the book her sister was reading");
    6. list.add("but it had no pictures or conversations in it");
    7. list.add("and what is the use of a book");
    8. list.add("thought Alice without pictures or conversation");
    9. RCollectionMapReduce<String, String, Integer> mapReduce
    10. = list.<String, Integer>mapReduce()
    11. .mapper(new WordMapper())
    12. .reducer(new WordReducer());
    13. // 统计词频
    14. Map<String, Integer> mapToNumber = mapReduce.execute();
    15. // 统计字数
    16. Integer totalWordsAmount = mapReduce.execute(new WordCollator());