-2

For this I will create 3 objects for 3 rows and store in arraylist

I am fetching data from sql db.The db for instance contains n records.For every row,we have a reqid.Suppose we have 6 rows in the record. For every unique req id we want to treat each row as an object in arraylist.So how do we create arraylist for each unique id in the loop? First 3 rows I want to store in one arraylist. Next two rows as objects in another arraylist.How to store such n unique reqids rows in n different arraylist through a loop?

Aziz
  • 23
  • 6

1 Answers1

1

Create a Map keyed on the record ID with the value being a List containing the Records matching that ID. Note, I'm waving my hand at the datatypes here - I assume you'll figure out what type to use for the ID and what you want to use for the Record.

Map<ID, List<Record>> recordMap = new HashMap<>();

Iterate over the ResultSet and check the Map to see if it already has a List for the ID of the current Record. If not found, you add it. Then add the Record to the List.

for (resultSet.next()) {
  Record record = parseRecord(resultSet);
  List<Record> records = null;
  if (recordMap.containsKey(record.getId()) {
    records = recordMap.get(record.getId()):
  } else {
    records = new ArrayList<>();
    recordMap.put(record.getId(), records);
  }
  records.add(record);
}
vsfDawg
  • 1,425
  • 1
  • 9
  • 12