0

I have a class which I am passing as a list. Some of the variables have default value, and I need to create around 5 objects form that class with specific fields.

public class Transaction{
  @JsonProperty("Amount")
  public String amount = "1390.00";
  @JsonProperty("Mnemonic")
  public String mnemonic = "NYU";
  @JsonProperty("Transaction_Code")
  public String transactionCode = "1435a";
  @JsonProperty("Time_Stramp")
  public String timeStramp = "2021-02-16-22.50.41.782000";
  @JsonProperty("AccountNo")
  public String accountNo = "15433276004350";
}

This is the class and I have mentioned that as a list class. public List<Transaction> transaction;

I want to create 5 objects with only mnemonic, transactionCode and timeStramp for Transaction.

In the Main class, I started doing like this. But I don't know how to pass the relevant fields and create objects for that fields.

    List <Transaction> transactions = new ArrayList<Transaction>();
    transactions.add(new Transaction(?));

How can I create 5 objects from the specified variables ( mnemonic, transactionCode and timeStramp)

Sample values

mnemonic transactionCode timeStramp
PRY 15s57 2021-03-14-23.40.45.781300
PCA 16a48 2021-04-21-17.30.15.331200
PRY 16t21 2021-04-26-23.45.45.764100
ASL 17q02 2021-05-12-18.20.25.232300
RRL 19m40 2021-08-04-04.10.34.536400

Please help.

Deepika
  • 737
  • 7
  • 23

1 Answers1

2

Option1: Try adding the setters and getters to the class then set the desired values using setters.

e.g.

List <Transaction> transactions = new ArrayList<Transaction>();
Transaction t1 = new Transaction();
t1.setMnemonic("PRY");
// Other setters

Transaction t2 = new Transaction();
t2.setMnemonic("PCA");
// Other setters

:
:
transactions.add(t1);
transactions.add(t2);

Option2: Create constructor with the available fields. Then pass desired values to the constructor.

e.g

public Transaction(String amout, String mnemonic, String transactionCode, String timeStramp, String accountNo)

  this.amout = amount;
  this.mnemonic = mnemonic;
  this.transactionCode = transactionCode;
  this.timeStramp = timeStramp;
  this.accountNo = accountNo;
}


 List <Transaction> transactions = new ArrayList<Transaction>();
    transactions.add(new Transaction(`<Pass the values here>`));
Nagaraju Chitimilla
  • 530
  • 3
  • 7
  • 23
  • And can we sort the objects? Normally we use collections.sort(), list.sort() and comparable. What can I use to sort the inputs using the timestramp without creating a new method? – Deepika Aug 30 '21 at 05:56
  • I hope this will answers your question: https://stackoverflow.com/questions/12542185/sort-a-java-collection-object-based-on-one-field-in-it – Nagaraju Chitimilla Aug 30 '21 at 06:17