Convert Kotlin Collections (.find, .map) into Java

Viewed 174

I need to convert the following kotlin code to java:

private fun processPurchases(allPurchases: List<Purchase>, purchasedProductsFetched: Boolean) {

    val validPurchases = allPurchases.filter {
        isPurchaseSignatureValid(it)
    }.map { purchase ->
        val skuDetails = fetchedSkuInfosList.find { it.skuId == purchase.sku }!!.skuDetails
        PurchaseInfo(
            generateSkuInfo(skuDetails),
            purchase
        )
    }
}

I am stuck after .map part and can't figure out what's going on...

private void processPurchases(List<Purchase> allPurchases, boolean purchasedProductsFetched) {
    
    List<Purchase> validPurchases = new ArrayList<>();

    for (Purchase purchase : allPurchases) {
        if (isPurchaseSignatureValid(purchase)) {
            validPurchases.add(purchase);
        }
    }
}

Can someone explain what to do next?

3 Answers

You could also take advantage Java streams and take a more functional like approach:

void process(List<Purchase> allPurchases, Boolean purchasedProductsFetched) {
    List<PurchaseInfo> validPurchases = allPurchases
            .stream()
            .filter(this::isPurchaseSignatureValid)
            .map(purchase ->
                    new PurchaseInfo(
                            fetchedSkuInfosList
                                    .stream()
                                    .filter(it -> it.getSkuId().equals(purchase.getSku()))
                                    .findFirst()
                                    .get()//the get here is as unsafe as the !! in kotlin
                                    .getSkuDetails(),
                            purchase
                    )
            ).collect(Collectors.toList());
}

Note, this replicates the mistakes from the given kotlin code. The null safety issue with !!, the unused purchasedProductsFetched property, and the unused validPurchases.

Firstly, validPurchases list needs PurchaseInfo type instead od Purchase. So you need to write smth like that:

validPurchases.add(PurchaseInfo(generateSkuInfo(skuDetails),purchase));

@Konrad Pękala answer helped me to understand in which direction to look.

private void processPurchases(List<Purchase> allPurchases, boolean purchasedProductsFetched) {
    if (!allPurchases.isEmpty()) {

        List<PurchaseInfo> validPurchases = new ArrayList<>();

        for (Purchase purchase : allPurchases) {
            if (isPurchaseSignatureValid(purchase)) {
                for (SkuInfo skuInfo : fetchedSkuInfoList) {
                    if (skuInfo.getSkuId().equals(purchase.getSku())) {
                        SkuDetails skuDetails = skuInfo.getSkuDetails();

                        PurchaseInfo purchaseInfo = new PurchaseInfo(generateSkuInfo(skuDetails), purchase);
                        validPurchases.add(purchaseInfo);
                    }
                }
            }
        }


    }
}
Related