
sirius.kernel.commons.PriorityCollector Maven / Gradle / Ivy
/*
* Made with all the love in the world
* by scireum in Remshalden, Germany
*
* Copyright by scireum GmbH
* http://www.scireum.de - [email protected]
*/
package sirius.kernel.commons;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Provides a pull pattern just like {@link DataCollector} with an externally supplied order.
*
* When asking methods to create or populate a {@link List} it's easier to create and pass along a
* PriorityCollector instead of having each method creating its own list and joining them afterwards.
*
* Using a PriorityCollector, several methods can be supplied with the same instance and generate a list or a
* custom (externally) ordering. This greatly simplifies creating extensible systems which are enhanced by
* sub-components and where order of elements matter. The final list is sorted by comparing the priority.
* Therefore if {@code a.priority < b.priority} then a will occur before b in the list.
*
* If the order of the provided elements does not matter, a {@link DataCollector} can be used.
*
* @param the type of values to be collected
* @see DataCollector
*/
public class PriorityCollector {
/**
* Provides a default constant which can be used if a collector is pre-populated with standard values and then
* enhanced by sub modules.
*
* Using an agreed upon standard value makes it easy for component creators to provide values which will be
* inserted before or after the default value.
*/
public static final int DEFAULT_PRIORITY = 100;
protected List> data = new ArrayList<>();
/**
* Creates a new PriorityCollector.
*
* Boilerplate method, so one doesn't need to re-type the type parameters.
*
* @param the type of value collect by the collector
* @return a new PriorityCollector
*/
public static PriorityCollector create() {
return new PriorityCollector<>();
}
/**
* Adds the given entity with the given priority.
*
* @param priority the priority to use for this element.
* @param entity the entity added to the collector.
*/
public void add(int priority, T entity) {
data.add(new ComparableTuple(priority, entity));
}
/**
* Adds the given entity with the default priority.
*
* @param entity the entity added to the collector.
* @see #DEFAULT_PRIORITY
*/
public void addDefault(T entity) {
data.add(new ComparableTuple(DEFAULT_PRIORITY, entity));
}
/**
* Returns the list of added entities sorted by priority.
*
* The comparator used is < - therefore if {@code a.priority < b.priority}
* then a will occur before b in the list.
*
* @return the list of entities ordered by priority ascending
*/
public List getData() {
Collections.sort(data);
return Tuple.seconds(data);
}
/**
* Returns the number of items added to this collector.
*
* @return the number of items in this collector
*/
public int size() {
return data.size();
}
@Override
public String toString() {
return data.toString();
}
}