Tuesday, July 12, 2011

Really simple functional extensions for Java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Util {
    public interface Predicate<T> {
        boolean check(T instance);
    }
   
    public interface Attr<T, A> {
        A get(T instance);
    }

    public static <T> List<T> truncate(List<T> list, int maxLength) {
        if (list.size() > maxLength) {
            return new ArrayList<T>(list.subList(0, maxLength));
        }
        return list;
    }

    public static <T> List<T> filter(List<T> list, Predicate<T> checker) {
        List<T> filtered = new ArrayList<T>();
        for (T item: list) {
            if (checker.check(item)) {
                filtered.add(item);
            }
        }
        return filtered;
    }
   
    public static <T> int count(List<T> list, Predicate<T> checker) {
        int count = 0;
        for (T item: list) {
            if (checker.check(item)) {
                count++;
            }
        }
        return count;
    }
   
    public static <T, A> Map<A, List<T>> rollup(List<T> list, Attr<T, A> attr) {
        Map<A, List<T>> result = new HashMap<A, List<T>>();
        for (T item: list) {
            A key = attr.get(item);
            List<T> itemList = result.get(key);
            if (itemList == null) {
                itemList = new ArrayList<T>();
                itemList.add(item);
                result.put(key, itemList);
            } else {
                itemList.add(item);
            }
        }
        return result;
    }
}

No comments: