Skip to content

Instantly share code, notes, and snippets.

@msbaek
Created November 14, 2015 09:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save msbaek/50e8d411881d6abdd4ec to your computer and use it in GitHub Desktop.
Save msbaek/50e8d411881d6abdd4ec to your computer and use it in GitHub Desktop.
convert one object to another object by using Function in guava
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import lombok.Data;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.List;
@Data
class ETradeInvestment {
private String key;
private String name;
private BigDecimal price;
}
@Data
class TdAmeritradeInvestment {
private int investmentKey;
private String investmentName;
private double investmentPrice;
public TdAmeritradeInvestment(int key, String name, double price) {
this.investmentKey = key;
this.investmentName = name;
this.investmentPrice = price;
}
}
public class ConvertFromOneObjectToAnotherTest {
@Test
public void name() {
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));
// convert a list of objects
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment