[英]Guava Transform Map<String, List<Double>> to List<TargetObject>
我必須將源對象轉換/轉換為目標對象。 請使用Guava查看下面的示例代碼。
下面是一個測試類,其中我有一個Source對象,如Map<String, List<Double>>
,我需要將其轉換為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
}
}
目標對象:
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;
}
}
您能否建議我是否可以使用Guava或任何其他好的API?
我想我可以按照以下方式進行...讓我知道是否有更好的方法...
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));
}
});
我會建議使用Guava FluentIterable進行此轉換,因為它會生成一個不可變的列表,在更安全的情況下更易於使用:
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();
使用番石榴列表 :
List<TargetObject> resultList = Lists.transform(source.entrySet(),
new Function<Entry<Integer, List<Integer>>, TargetObject>(){...});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.