001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.kernel.util;
016    
017    import java.util.Enumeration;
018    import java.util.NoSuchElementException;
019    
020    /**
021     * @author Shuyang Zhou
022     */
023    public class MappingEnumeration<T, R> implements Enumeration<R> {
024    
025            public MappingEnumeration(Enumeration<T> enumeration, Mapper<T, R> mapper) {
026                    this.enumeration = enumeration;
027                    this.mapper = mapper;
028    
029                    nextElement = nextMappedElement();
030            }
031    
032            @Override
033            public boolean hasMoreElements() {
034                    if (nextElement != null) {
035                            return true;
036                    }
037    
038                    return false;
039            }
040    
041            @Override
042            public R nextElement() {
043                    if (nextElement == null) {
044                            throw new NoSuchElementException();
045                    }
046    
047                    R nextElement = this.nextElement;
048    
049                    this.nextElement = nextMappedElement();
050    
051                    return nextElement;
052            }
053    
054            public interface Mapper<T, R> {
055    
056                    public R map(T t);
057    
058            }
059    
060            protected final R nextMappedElement() {
061                    while (enumeration.hasMoreElements()) {
062                            R element = mapper.map(enumeration.nextElement());
063    
064                            if (element != null) {
065                                    return element;
066                            }
067                    }
068    
069                    return null;
070            }
071    
072            protected final Enumeration<T> enumeration;
073            protected final Mapper<T, R> mapper;
074            protected R nextElement;
075    
076    }