0

I have a list which is a java object like below.

public class TaxIdentifier {
public String id;
public String gender;
public String childId; 
public String grade,
public String isProcessed;
////...///

getters and setters

///....///
}

Records in DB looks like below,
id   gender childId grader isProcessed
11      M     111       3       Y
12      M     121       4       Y
11      M     131       2       Y
13      M     141       5       Y
14      M     151       1       Y
15      M     161       6       Y   


List<TaxIdentifier> taxIdentifierList = new ArrayList<TaxIdentifier>();

for (TaxIdentifier taxIdentifier : taxIdentifierList) {             


}

while I process for loop and get the id = 11, i have to check if there are other records with id = 11 and process them together and do a DB operation and then take the next record say in this case 12 and see if there are other records with id = 12 and so on.

One option is i get the id and query the DB to return all id = 11 and so on. But this is too much back and forth with the DB.

What is the best way to do the same in java? Please advice.

Geek
  • 3,187
  • 15
  • 70
  • 115
  • Can we see (the relevant parts of) what's inside the `for` loop? I'm having a little trouble understanding what you're doing in there and what the problem is. Are the `id`s being created in java and saved to the database? Or read out of the database and used for comparisons in java? Please provide an mcve: https://stackoverflow.com/help/mcve – nvioli Mar 28 '19 at 18:20
  • 1
    why don't you use hash map and group data on id? – Syed Mehtab Hassan Mar 28 '19 at 18:22
  • @Syed Mehtab Hassan - Can you please explain how this can be done. – Geek Mar 28 '19 at 18:33
  • 1
    @JNPW https://stackoverflow.com/a/21678611/11046080 – Syed Mehtab Hassan Mar 28 '19 at 18:35

2 Answers2

1

If you anyway need to process all the records in the corresponding database table - you should retrieve all of them in 1 database roundtrip.

After that, you can collect all your TaxIdentifier records in dictionary data structure and process in whatever way you want.

The brief example may look like this:

Map<String, List<TaxIdentifier>> result = repositoty.findAll().stream().collect(Collectors.groupingBy(TaxIdentifier::getId));

Here all the TaxIdentifier records are grouped by TaxIdentifier's id (all the records with id equals "11") can be retrieved and processed this way:

List<TaxIdentifier> taxIdentifiersWithId11 = result.get("11");
star67
  • 1,505
  • 7
  • 16
0

I would leverage the power of your database. When you query, you should order your query by id in ascending order. Not sure which database you are using but I would do:

SELECT * FROM MY_DATABASE WHERE IS_PROCESSED = 'N' ORDER BY ID ASC; 

That takes the load of sorting it off of your application and onto your database. Then your query returns unprocessed records with the lowest id's on top. Then just sequentially work through them in order.

Josh
  • 115
  • 1
  • 15