Apply a function f to all elements of collection as to produce a new collection bs. - Java java.util

Java examples for java.util:Collection Creation

Description

Apply a function f to all elements of collection as to produce a new collection bs.

Demo Code

/**/*from  ww  w .ja va 2 s. c  om*/
 *  Copyright 2009, 2010 The Regents of the University of California
 *  Licensed under the Educational Community License, Version 2.0
 *  (the "License"); you may not use this file except in compliance
 *  with the License. You may obtain a copy of the License at
 *
 *  http://www.osedu.org/licenses/ECL-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an "AS IS"
 *  BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 *  or implied. See the License for the specific language governing
 *  permissions and limitations under the License.
 *
 */
import java.util.Collection;
import java.util.function.Function;

public class Main {
  /**
   * Apply a function <code>f</code> to all elements of collection <code>as</code>
   * to produce a new collection <code>bs</code>.
   * <p/>
   * An (empty) instance of the target collection has to be provided explicitly.
   *
   * @param as
   *          the source collection
   * @param bs
   *          the (empty) target collection
   * @param f
   *          the function to apply to each element of <code>as</code>
   */
  public static <A, B, BB extends Collection<B>> BB map(Collection<A> as, BB bs, Function<A, B> f) {
    for (A x : as) {
      bs.add(f.apply(x));
    }
    return bs;
  }

  /**
   * Apply a function <code>f</code> to all elements of collection <code>as</code>
   * to produce a new collection <code>bs</code>.
   * <p/>
   * The type of collection <code>as</code> needs a parameterless constructor.
   * <p/>
   * Please note that since java does not support higher-order polymorphism --
   * which is needed to capture the type of the collection -- some casting on the
   * client side may still be necessary.
   *
   * @throws RuntimeException
   *           if the target collection cannot be created
   */
  public static <A, B> Collection<B> map(Collection<A> as, Function<A, B> f) {
    Collection<B> b = buildFrom(as);
    for (A x : as) {
      b.add(f.apply(x));
    }
    return b;
  }

  private static <A, B> Collection<A> buildFrom(Collection<B> as) {
    try {
      return as.getClass().newInstance();
    } catch (Exception e) {
      throw new IllegalArgumentException("Type " + as.getClass() + " needs a parameterless constructor");
    }
  }
}

Related Tutorials