Guava学习笔记:List转换(int->String)

method1:

package com.amg.test;

import java.util.List;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;

public class Integer2String {

	public static void main(String[] args) {
		Function function = new Function<Integer, String>() {
			@Override
			public String apply(Integer input) {
				Preconditions.checkArgument(null != input && !"".equals(input), "input is null!");
				return String.valueOf(input);
			}
		};
		List<Integer> fromList = Lists.newArrayList(111, 33, 222, 675432);
		List<String> to = Lists.transform(fromList, function);

		for (int i = 0; i < fromList.size(); i++) {
			System.out.println(to.get(i));
		}
	}

}

 

method2:

package com.amg.test;

import java.util.List;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;

public class Integer2String {

	public static void main(String[] args) {
		List<Integer> fromList = getIntList();
		List<String> to = transferInt2String(fromList);
		for (String str : to) {
			System.out.println(str);
		}
	}

	public static List<Integer> getIntList() {
		return Lists.newArrayList(111, 33, 222, 675432);
	}

	public static List<String> transferInt2String(List<Integer> fromList) {

		return Lists.transform(fromList, new Function<Integer, String>() {
			@Override
			public String apply(Integer input) {
				Preconditions.checkArgument(null != input && !"".equals(input),
						"input is null!");
				return String.valueOf(input);
			}
		});
	}

}

 运行结果:

111
33
222
675432

 

你可能感兴趣的:(java,guava,list,String)