Java collection/map apply method equivalent?

后端 未结 8 483
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-13 19:27

I would like to apply a function to a Java collection, in this particular case a map. Is there a nice way to do this? I have a map and would like to just run trim() on all t

相关标签:
8条回答
  • 2020-12-13 20:22

    I have come up with a "Mapper" class

    public static abstract class Mapper<FromClass, ToClass> {
    
        private Collection<FromClass> source;
    
        // Mapping methods
        public abstract ToClass map(FromClass source);
    
        // Constructors
        public Mapper(Collection<FromClass> source) {
            this.source = source;
        }   
        public Mapper(FromClass ... source) {
            this.source = Arrays.asList(source);
        }   
    
        // Apply map on every item
        public Collection<ToClass> apply() {
            ArrayList<ToClass> result = new ArrayList<ToClass>();
            for (FromClass item : this.source) {
                result.add(this.map(item));
            }
            return result;
        }
    }
    

    That I use like that :

    Collection<Loader> loaders = new Mapper<File, Loader>(files) {
        @Override public Loader map(File source) {
            return new Loader(source);
        }           
    }.apply();
    
    0 讨论(0)
  • 2020-12-13 20:28

    Whether you can modify your collection in-place or not depends on the class of the objects in the collection.

    If those objects are immutable (which Strings are) then you can't just take the items from the collection and modify them - instead you'll need to iterate over the collection, call the relevant function, and then put the resulting value back.

    0 讨论(0)
提交回复
热议问题