如何从流中的模型对象获取字段列表并映射到另一个模型对象?

时间:2019-04-19 03:53:05

标签: java java-stream

我正在尝试使用流从模型对象列表中获取字段列表,并映射到另一个对象列表,但这给了我以下错误。

enter image description here

List<FinalTestModel> testModels2 = new ArrayList<>();
testModels2 =     testModels.parallelStream().filter(item -> 
item.getReceiverPtyId().equalsIgnoreCase("TestId"))
            .flatMap(e -> Stream.of(e.getMonthM(),  e.getRecevingAmount(), e.getRecevingCurrency(),
                e.getBTransactionCount())).collect(Collectors.toList());


Input = [TestModel(monthM=May, receiverName=A, receiverC=India, recevingAmount=0.00000, recevingCurrency=KRW, bTransactionCount=1, transactionCount=0), TestModel(monthM=June, receiverName=A, receiverC=India, recevingAmount=10.00000, recevingCurrency=KRW, bTransactionCount=2, transactionCount=0), TestModel(monthM=July, receiverName=A, receiverC=India, recevingAmount=0.00000, recevingCurrency=KRW, bTransactionCount=0, transactionCount=0))]
Expected Output Result = [FinalTestModel(monthM=May, recevingAmount=0.00000, recevingCurrency=KRW, bTransactionCount=1), FinalTestModel(monthM=June, recevingAmount=10.00000, recevingCurrency=KRW, bTransactionCount=2),FinalTestModel(monthM=July, recevingAmount=10.00000, recevingCurrency=KRW, bTransactionCount=10)]

2 个答案:

答案 0 :(得分:1)

您正在创建模型属性流,而不是模型对象。创建FinalTestModel实例应解决以下问题:

testModels2 =     testModels.parallelStream()
    .filter(item -> item.getReceiverPtyId().equalsIgnoreCase("TestId"))
    .map(e -> new FinalTestModel(e.getMonthM(), e.getRecevingAmount(), e.getRecevingCurrency(), e.getBTransactionCount()))
    .collect(Collectors.toList());
如果要构造多个对象,

flatMap(... Stream.of(new FinalTestModel(...)))会很有意义。但是这里只有一个。

答案 1 :(得分:1)

下面的代码应该可以工作

testModels2 =     testModels.parallelStream()
.filter(item -> item.getReceiverPtyId().equalsIgnoreCase("TestId"))
.map(e -> new FinalTestModel(....))
.collect(Collectors.toList());