I am trying to map an array of objects to another array with different kind of objects, I used to do this using streams in java 8 it was pretty straight forward, instantiate an object set its values and return the object. I just switched to Kotlin and really sometimes is more confusing to do this kind of operations. All the examples I found are really simple and could not find something I want.
I have this BalanceMap class:
data class BalanceMap @JsonCreator constructor(
var balType: String,
var value: Any
)
I am getting the data from web service.
val balances: List<AcctBal> = res.getAcctBals();
the AcctBal class looks like this
public class AcctBal {
@SerializedName("CurAmt")
@Expose
private CurAmt curAmt;
@SerializedName("Desc")
@Expose
private String desc;
@SerializedName("ExpDt")
@Expose
private LocalDateTime expDt;
}
and try to map that response to var balanceList: List<BalanceMap>
balances.map {}
--> var balanceList: List<BalanceMap> = balances.map { t -> fun AcctBal.toBalanceMap() = BalanceMap(
balType = "",
value = ""
)}
I want to do something like this:
List<ProductDetail> details = acctBal.stream().filter(f -> f.getBalType() != null).map(e -> {
String bal = e.getBalType();
if (avalProductInfo.getBankId().equals("00010016")) {
bal = e.getBalType();
}
ProductDetail detail = new ProductDetail();
detail.setItem(bal);
if (e.getCurAmt() != null) {
detail.setValue(e.getCurAmt().getAmt().toString());
} else if (e.getRelationDt() != null) {
detail.setValue(e.getRelationDt().toGregorianCalendar().getTimeInMillis());
} else if (e.getMemo() != null) {
detail.setValue(e.getMemo());
}
return detail;
}).collect(toList());
I've been experimenting but is always wrong, any help will be highly appreciated. Happy coding!
some quick prototyping
details = acctBal
.filter{ f -> f.getBalType() != null }
.map { it -> mapToProductDetail (it) }
you can have a look here
Thanks to @Hakob Hakobyan for pointing in the right direction,
I left my solution like this:
fun mapRs(rs: AthProductResponse): BalanceByAccountRs {
val res = rs.getPartyAcctRelRec();
val balances: List<AcctBal> = res.getAcctBals();
val account = Account(res.getPartyAcctRelInfo().depAcctId.acctId, res.getPartyAcctRelInfo().depAcctId.acctType)
var balanceList: List<BalanceMap> = balances
.filter { f -> f.getDesc() != null }
.map { it -> mapToProductDetail(it) }
.toList()
return BalanceByAccountRs(account, balanceList)
}
fun mapToProductDetail(bal: AcctBal): BalanceMap {
var propertyValue: Long = 0L;
if(bal.getExpDt() != null) {
propertyValue = Timestamp.valueOf(bal.getExpDt()).getTime()
} else {
propertyValue = bal.getCurAmt().getAmt().toLong()
}
return BalanceMap(bal.getDesc(), propertyValue)
}
Just in case someone is going through the same. Happy coding
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With