All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.dihedron.patterns.functional.$ Maven / Gradle / Ivy

/**
 * Copyright (c) 2012-2014, Andrea Funto'. All rights reserved. See LICENSE for details.
 */ 

package org.dihedron.patterns.functional;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.dihedron.core.License;

/**
 * @author Andrea Funto'
 */
@License
public class $ {

	/**
	 * The iterator, used to scan the the input collection.
	 */
	Iterator iterator;
	
	/**
	 * Constructor.
	 * 
	 * @param list
	 *   a list to iterate on.
	 */
	public  $(List list) {
		iterator = list.iterator();
	}
	
	/**
	 * Constructor.
	 *
	 * @param set
	 *   a set to iterate on.
	 */
	public  $(Set set) {
		iterator = set.iterator();
	}
	
	/**
	 * Constructor.
	 *
	 * @param map
	 *   a map to iterate on, entry-wise.
	 */
	public  $(Map map) {
		iterator = map.entrySet().iterator();
	}
	
	/**
	 * Iterates over the collection elements or entries and passing each of them 
	 * to the given implementation of the functor interface; if state needs to be 
	 * propagated, it can be instantiated and returned by the first invocation of 
	 * the functor and it will be passed as a parameter to the invocation of the
	 * functor on the the following elements of the collection.
	 * 
	 * @param functor
	 *   an implementation of the {@code $} functor interface.
	 * @return
	 *   the result of the iteration.
	 */
	public  S forEach(Fx functor) {
		return forEach(null, functor);
	}
	
	/**
	 * Iterates over the collection of elements or entries, passing each of them 
	 * to the given implementation of the functor interface; if state is provided
	 * it will be it passed as a parameter to the invocations of the functor
	 * on the following elements of the collection.
	 * 
	 * @param state
	 *   a state variable to be used during the processing.
	 * @param functor
	 *   an implementation of the {@code $} functor interface.
	 * @return
	 *   the result of the iteration.
	 */
	@SuppressWarnings("unchecked")
	public  S forEach(S state, Fx functor) {
		S newState = state;
		while(iterator.hasNext()) {
			newState = functor.apply(newState, (E)iterator.next());
		}
		return newState;		
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy