Skip to content
Advertisement

How to merge two lists with different variable types

As the question states I’m wondering what the best way to merge two lists together that have different variable types. I’m unsure if the way I’m going about this problem is the correct way so I’m happy to take all advice regarding this. Basically I’m making a banking application. When the user finishes some transaction data is added to a txt file of the form (Type Date Amount). I want the user to then be able to do some more transactions later and these new transactions added to the end of this txt file.

My Issue is that when I re read the users previous transactions I read them in as a List of strings

BufferedReader br = null;

    try {

        br = new BufferedReader(new FileReader(account.getName()+"Transactions.txt"));

        String line;
        while ((line = br.readLine()) != null) {
            transactions.add(line);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            br.close();
        }

however the list of transactions to add to my txt file is of the type Transaction not a String.

List<Transaction> transactionsToAdd = new ArrayList<Transaction>()

As an example here is some code in the case the user makes a deposit.

    case 1:
            amount = scanner.DepositScanner();
            balance = account.Deposit(balance, amount);
            System.out.print("Your new balance is: " + balance);

            String depositFullDate = dateManager.getDateAsString();
            Transaction depositTransaction = new Transaction("Depsoit", amount, depositFullDate);
            transactionsToAdd.add(depositTransaction);

            break;

Ideally I want the code to read in the users previous transactions, add their new transactions to the end of the txt file and then save all of these to the same txt file when the user is finished. Is there either a way to read in the users previous transactions as type Transaction rather than String, or combine these two lists somehow to give me a big list to save to my txt file.

My transaction class is below

public class Transaction {
String details;
String date;

Double amount;



public String getDate() {
    return date;
}
public void setDate(String date) {
    this.date = date;
}
public Transaction(String details, double amount, String date) {
    super();
    this.details = details;
    this.date = date;
    
    this.amount = amount;
}
public String getDetails() {
    return details;
}
public void setDetails(String details) {
    this.details = details;
}
public Double getAmount() {
    return amount;
}
public void setAmount(double amount) {
    this.amount = amount;
}

}

Edit 1 – Added code for my transaction class

Advertisement

Answer

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement