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

org.jvnet.jaxb2.maven2.util.CollectionUtils Maven / Gradle / Ivy

package org.jvnet.jaxb2.maven2.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

public class CollectionUtils {

	public static class PositiveComparator>
			implements Comparator {
		public int compare(V o1, V o2) {
			if (o1 == null && o2 == null)
				return 0;
			else if (o1 == null)
				return 1;
			else if (o2 == null)
				return -1;
			else
				return o1.compareTo(o2);
		}
	}

	public static class NegativeComparator>
			implements Comparator {
		public int compare(V o1, V o2) {
			if (o1 == null && o2 == null)
				return 0;
			else if (o1 == null)
				return -1;
			else if (o2 == null)
				return 1;
			else
				return -o1.compareTo(o2);
		}
	}

	public interface Function {
		public V eval(T argument);
	}

	public static  Collection apply(Collection collection,
			Function function) {
		final List list = new ArrayList(collection.size());
		for (T t : collection) {
			list.add(function.eval(t));
		}
		return list;
	}

	public static  V bestValue(Collection collection,
			CollectionUtils.Function function, Comparator comparator) {

		if (collection == null || collection.isEmpty())
			return null;

		final Iterator i = collection.iterator();
		V candidateValue = function.eval(i.next());

		while (i.hasNext()) {
			final V nextValue = function.eval(i.next());
			if (comparator.compare(candidateValue, nextValue) < 0) {
				candidateValue = nextValue;
			}
		}
		return candidateValue;
	}

	public static Comparator LT = new NegativeComparator();

	public static Comparator GT = new PositiveComparator();

	public static > Comparator lt() {
		@SuppressWarnings("unchecked")
		final Comparator comparator = (Comparator) LT;
		return comparator;
	}

	public static > Comparator gt() {
		@SuppressWarnings("unchecked")
		final Comparator comparator = (Comparator) GT;
		return comparator;
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy