番石榴变换地图<字符串、列表<Double>>到列表<TargetObject>



我必须将源对象转换/转换为目标对象。请参阅下面使用番石榴的示例代码。

下面是一个测试类,其中我有一个 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;
    }
}

你能建议我是否可以用番石榴或任何其他好的 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>(){...});

最新更新