Reputation: 33
Suppose I have a class Transaction:
public class Transaction {
private String tId;
private String tStatus;
}
Now I create another class Customer:
public class Customer {
private String cId;
private List<Transaction> transaction;
}
Now, if I get a String list of tIds and a separate String list of tStatus, how do I merge these two lists to make Transaction type List in Java?
Upvotes: 2
Views: 68
Reputation: 311163
Assuming Transaction
has a constructor from these two strings, and assuming the lists have the same length, you can iterate over both of them and create a list of Transactions
:
List<String> tIds = /* probably a method argument? */
List<String> tStatuses = /* probably a method argument? */
if (tIds.size() != tStatuses.size()) {
throw new IllegalArgumentException("list sizes don't match");
}
List<Transaction> result = new ArrayList<>(tIds.size());
for (int i = 0; i < tIds.size(); ++i) {
result.add(new Transaction(tIds.get(i), tStatuses.get(i)));
}
Or, arguably more elegantly, use a stream instead of a loop:
List<Transaction> result =
IntStream.range(0, tIds.size())
.mapToObj(i -> new Transaction(tIds.get(i), tStatuses.get(i)))
.collect(Collectors.toList());
Upvotes: 4