在之前的博文中介绍了guava强大的filter和transform,能转变各类东西,下面继续深入学习下,废话少说:
1) 将string转换为enum:
在guava 16中,可以将string转换为enum,
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY;
}
其中可以使用stringConverter的方法,
@Test
public void transform_string_to_enum () {
List<String> days = Lists.newArrayList(
"WEDNESDAY",
"SUNDAY",
"MONDAY",
"WEDNESDAY");
Function<String, Day> stringToDayEnum = Enums.stringConverter(Day.class);
Iterable<Day> daysAsEnum = Iterables.transform(days, stringToDayEnum);
for (Day day : daysAsEnum) {
System.out.println(day);
}
}
2 第2个应用场景,就是可以对一些对象进行转换,比如从一个对象转换到另外一个对象,如假设有两个对象:
public class ETradeInvestment {
private String key;
private String name;
private BigDecimal price;
...
}
public class TdAmeritradeInvestment {
private int investmentKey;
private String investmentName;
private double investmentPrice;
...
}
@Test
public void convert_tdinvestment_etradeinvestment () {
List<TdAmeritradeInvestment> tdInvestments = Lists.newArrayList();
tdInvestments.add(new TdAmeritradeInvestment(555, "Facebook Inc", 57.51));
tdInvestments.add(new TdAmeritradeInvestment(123, "Micron Technology, Inc.", 21.29));
tdInvestments.add(new TdAmeritradeInvestment(456, "Ford Motor Company", 15.31));
tdInvestments.add(new TdAmeritradeInvestment(236, "Sirius XM Holdings Inc", 3.60));
Function<TdAmeritradeInvestment, ETradeInvestment> tdToEtradeFunction = new Function<TdAmeritradeInvestment, ETradeInvestment>() {
public ETradeInvestment apply(TdAmeritradeInvestment input) {
ETradeInvestment investment = new ETradeInvestment();
investment.setKey(Ints.stringConverter().reverse()
.convert(input.getInvestmentKey()));
investment.setName(input.getInvestmentName());
investment.setPrice(new BigDecimal(input.getInvestmentPrice()));
return investment;
}
};
List<ETradeInvestment> etradeInvestments = Lists.transform(tdInvestments, tdToEtradeFunction);
System.out.println(etradeInvestments);
}
可以看到,假如要把数据库中获得的记录中的LIST中的各个对象,一次过进行变换复制,更改其中某些值的话,用这个方法就最好了;
如转换一个对象,容易办:
ETradeInvestment faceBookInvestment = tdToEtradeFunction
.apply(new TdAmeritradeInvestment(555, "Facebook Inc", 57.51));
3 把list转为MAP,其中要用到guava中map的工具类了
@Test
public void transform_list_to_map () {
List<TdAmeritradeInvestment> tdInvestments = Lists.newArrayList();
tdInvestments.add(new TdAmeritradeInvestment(555, "Facebook Inc", 57.51));
tdInvestments.add(new TdAmeritradeInvestment(123, "Micron Technology, Inc.", 21.29));
tdInvestments.add(new TdAmeritradeInvestment(456, "Ford Motor Company", 15.31));
tdInvestments.add(new TdAmeritradeInvestment(236, "Sirius XM Holdings Inc", 3.60));
ImmutableMap<Integer, TdAmeritradeInvestment> investmentMap = Maps
.uniqueIndex(tdInvestments,
new Function<TdAmeritradeInvestment, Integer>() {
public Integer apply(TdAmeritradeInvestment input) {
return new Integer(input.getInvestmentKey());
}
});
System.out.println(investmentMap);
}