How to Convert Between Types with Guava

import static java.lang.System.out;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.common.base.Function;
import com.google.common.collect.Iterators;

public final class GuavaSample {

  public static void main(final String[] args) {
    final List<String> lst = new ArrayList<String>();

    lst.add("0");

    lst.add("1");

    final Iterator<Integer> iter = Iterators.transform(lst.iterator(), new Function<String, Integer>() {

        public Integer apply(final String input) {

          try {
            return Integer.parseInt(input);
          } catch (final Exception e) {
          }

          return 0;
        }

      }); // or Collections2, Iterables

    while (iter.hasNext())
      out.println(iter.next());

  }

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s