Currently I have list of object(Entitlement) array, from that array I have to Iterate and add to the list of Card object, any way to do this. Please let me know.
Now I don't want entire data from entitlements list, need only id and name and want this to be store into Card object. How i can achieve this, using stream?
public static class Entitlement {
public String id;
public String name;
public String serviceEntitlementNumber;
public String serviceType;
public String alphaId;
public String modifiedTime;
} //Entitlement obj –
public static class Card {
public String id;
public String name;
} // card obj
List <MerchantGatewayEntitlement> entitlements =
getEntitlements(merchantId);
List <Card> cards = new ArrayList <>();
for (MerchantGatewayEntitlement entitlement : entitlements) {
how to add this list to card list.
}
Why use streams? It has its advantages but it also has quite a bit of overhead. Nothing wrong with using a loop. And don't worry about "improving"
existing working code
using Java 8 features.
I don't know what your Card
class looks like but there is nothing wrong with the following:
List<Card> cardList = new ArrayList<>();
for (MerchantGatewayEntitlement entitlement : entitlements) {
cardList.add(new Card(entitlement.getCard(), entitlement.getSomethingElse()));
}
or other Java 8 options.
entitlements.forEach(ent-> {
cardList.add(new Card(ent.getCard(), ent.getSomethingElse()));
});
But if you insist on using a stream solution and you need to be able to modify
the returned list, then do it like this.
List<Card> cardList = entitlements.stream()
.map(ent -> new
Card(ent.getCard(),ent.getSomethingElse()))
.collect(Collectors.toCollection(ArrayList::new));