I have to transform/convert source object into target object. Please see the sample code below using Guava.
Below is a test class where i have a Source object as Map<String, List<Double>>
which i need to transform it to Target
.
public class TestMapper {
public static void main(String[] args) {
String key = "123AA";
List<Double> values = new ArrayList<Double>();
values.add(15.0);
values.add(3.0);
values.add(1.0);
//source
Map<String, List<Double>> source = new HashMap<String, List<Double>>();
source.put(key, values);
//target
List<TargetObject> target = new ArrayList<>();
//transformation logic
}
}
Target Object:
public class TargetObject
{
private int pivotId;
private int amt1;
private int amt2;
private int amt3;
public int getPivotId() {
return pivotId;
}
public void setPivotId(int pivotId) {
this.pivotId = pivotId;
}
public int getAmt1() {
return amt1;
}
public void setAmt1(int amt1) {
this.amt1 = amt1;
}
public int getAmt2() {
return amt2;
}
public void setAmt2(int amt2) {
this.amt2 = amt2;
}
public int getAmt3() {
return amt3;
}
public void setAmt3(int amt3) {
this.amt3 = amt3;
}
}
Can you please suggest if i can do with Guava or any other good API?
I think i can do it in below manner...Let me know if ther is better way to do it...
Map<Integer, TargetObject> transformEntries =
Maps.transformEntries(source, new EntryTransformer<Integer, List<Integer>, TargetObject>() {
@Override
public TargetObject transformEntry(Integer key, List<Integer> values) {
return new TargetObject(key, values.get(0), values.get(1), values.get(2));
}
});
I would recommend Guava FluentIterable for this transformation, since it produces an immutable list that is easier on more safe to work with:
List<TargetObject> resultList = FluentIterable.from(source.entrySet()).transform(
new Function<Map.Entry<String, List<Double>>, TargetObject>() {
@Override
public TargetObject apply(Map.Entry<String, List<Double>> integerListEntry) {
...
}
}).toList();
Use Guava Lists :
List<TargetObject> resultList = Lists.transform(source.entrySet(),
new Function<Entry<Integer, List<Integer>>, TargetObject>(){...});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.