DaveAKing / guava-libraries

Automatically exported from code.google.com/p/guava-libraries
Apache License 2.0
0 stars 0 forks source link

Add map and reduce functions to the collections API #1601

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
A type-safe map and reduce function in the collections API would be helpful. 
Shown are a "List" and general "Collection" variant. These are inspired by 
underscore.js.

//General collection map function
    public static <T, S> Collection<S> map(Collection<T> collection, IMapCollection<T, S> map) {
        if( collection == null )
            return null;
        List<S> list = new ArrayList<S>(collection.size());
        for(T t : collection){
            list.add(map.accept(t, collection));
        }
        return list;
    }

    public static interface IMapCollection<T, S> {
        public S accept(T t, Collection<T> list);
    }

//List map function
    public static <T, S> List<S> map(List<T> collection, IMapList<T, S> map) {
        if( collection == null )
            return null;
        List<S> list = new ArrayList<S>(collection.size());
        int i=0;
        for(T t : collection){
            list.add(map.accept(t, i++, collection));
        }
        return list;
    }

    public static interface IMapList<T, S> {
        public S accept(T t, int index, List<T> list);
    }

//General collection reduce function
    public static <T,S> S reduce(Collection<T> collection, IReduceCollection<T, S> reduce, S memo) {
        if( collection == null )
            return null;
        for(T t : collection){
            memo = reduce.accept(memo, t, collection);
        }
        return memo;
    }

    public static interface IReduceCollection<T, S> {
        public S accept(S memo, T obj, Collection<T> list);
    }

//List reduce function
    public static <T,S> S reduce(List<T> list, IReduceList<T, S> reduce, S memo) {
        if( list == null )
            return null;
        int i=0;
        for(T t : list){
            memo = reduce.accept(memo, t, i++, list);
        }
        return memo;
    }
    public static interface IReduceList<T, S> {
        public S accept(S memo, T obj, int index, List<T> list);
    }

Original issue reported on code.google.com by adam.hal...@gmail.com on 3 Dec 2013 at 7:53

GoogleCodeExporter commented 9 years ago

Original comment by lowas...@google.com on 3 Dec 2013 at 7:56

GoogleCodeExporter commented 9 years ago
(Mapping is already provided, so this is a dupe of reduce/fold.)

Original comment by lowas...@google.com on 3 Dec 2013 at 7:56

GoogleCodeExporter commented 9 years ago
This issue has been migrated to GitHub.

It can be found at https://github.com/google/guava/issues/<issue id>

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:10

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 3 Nov 2014 at 9:08