Created
November 14, 2015 09:01
-
-
Save msbaek/50e8d411881d6abdd4ec to your computer and use it in GitHub Desktop.
convert one object to another object by using Function in guava
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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