package com.case;import java.util.List;import com.google.common.base.Function;import com.google.common.collect.Lists;/** * Step on the pit with guava * * @author James * @version $Id: GuavaListsTransFormCase.java, v 0.1 2017年3月24日 下午8:36:36 James Exp $ */public class GuavaListsTransFormCase { public static void main(String[] args) { List as = Lists.newArrayList(); A a = new A(); a.setC(1); as.add(a); try { System.out.println("case1 start"); transFormCase1(as); } catch (Exception e) { System.out.println(e.getMessage()); } finally { System.out.println("case1 end"); } try { System.out.println("case2 start"); transFormCase2(as); } catch (Exception e) { System.out.println(e.getMessage()); } finally { System.out.println("case2 end"); } } private static List transFormCase1(List as) { return Lists.transform(as, new Function () { @Override public B apply(A input) { B b = new B(); b.setC(input.getC() / 0); //...variables return b; } }); } private static List transFormCase2(List as) { return Lists.newArrayList(Lists.transform(as, new Function () { @Override public B apply(A input) { B b = new B(); b.setC(input.getC() / 0); //...variables return b; } })); }}class A { private int c; //...variables public int getC() { return c; } public void setC(int c) { this.c = c; }}class B { private int c; //...variables public int getC() { return c; } public void setC(int c) { this.c = c; }}
执行结果:
case1 startcase1 endcase2 start/ by zerocase2 end
case2比case1多了一步,在使用Lists.transform的时候将转换结果,用Lists.newArrayList 重新产生一个新的list。以确保function内的代码(比如调用远程方法,操作数据库等容易抛出异常的代码)立即被执行,而不是在要使用的时候执行,从而导致异常没有在预期的地方被捕获。