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?
Asked
Active
Viewed 263 times
-2
-
Try a `HashMap
>` – f1sh Apr 27 '20 at 10:23 -
@f1sh can you plz give an example..I am new to java – Aziz Apr 27 '20 at 10:26
-
@f1sh actually I wanna just know how to create arraylist on the go..as in the loop . – Aziz Apr 27 '20 at 10:27
-
1What have you tried? See [ask] – mtk Apr 27 '20 at 10:31
1 Answers
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