transform a list by function - Java java.util

Java examples for java.util:List Operation

Description

transform a list by function

Demo Code

import java.util.AbstractCollection;
import java.util.AbstractList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;

public class Main {
  public static <S, T> List<T> transform(final List<? extends S> source, final Function<S, T> transformer) {
    return new AbstractList<T>() {
      @Override//from w ww  . j  a  v a  2  s  .  c o  m
      public T get(int index) {
        return transformer.apply(source.get(index));
      }

      @Override
      public int size() {
        return source.size();
      }
    };
  }

  public static <S, T> Collection<T> transform(final Collection<? extends S> source, final Function<S, T> transformer) {
    return new AbstractCollection<T>() {
      @Override
      public Iterator<T> iterator() {
        final Iterator<? extends S> it = source.iterator();
        return new Iterator<T>() {
          @Override
          public boolean hasNext() {
            return it.hasNext();
          }

          @Override
          public T next() {
            return transformer.apply(it.next());
          }

          @Override
          public void remove() {
            it.remove();
          }
        };
      }

      @Override
      public int size() {
        return source.size();
      }
    };
  }
}

Related Tutorials