0

I have a piece of code as follows and the idea is basically to process a fixed amount of items/ids each time based on LIMIT:

    List<Integer> employeeId = new ArrayList<>();
    for(Department d: getDepartments() {        
      for(Person p: d.getPersons()) {
         employeeId.add(p.getId());  
         if(employeeId.size() < LIMIT) {
          continue;
         }
         processIds(employeeId);  
         employeeId.clear();
       }
    }
    if(!employeeId.isEmpty()) {
      processIds(employeeId);  
    }

My question is: Is there a more idiomatic way e.g. using streams to write the code and would that be more performant?

Note: Reason I am asking for context is that I have not used streams in Java hence I am trying to understand more the usage. It is not the case that the code has been profiled and is slow

Jim
  • 3,845
  • 3
  • 22
  • 47
  • 1
    Refer https://stackoverflow.com/questions/5824825/efficient-way-to-divide-a-list-into-lists-of-n-size#:~:text=1.To%20partition%20in%20N%20equal%20parts%3A%20private%20%3CT%3E,2.%20To%20partition%20in%20sets%20of%20N%20items%3A – Ashraff Ali Wahab Nov 02 '22 at 18:24
  • @AshraffAliWahab: The answers there either use a library (which I can't use) or don't explain what is better with the approach. – Jim Nov 02 '22 at 18:25
  • Look at all the answers, you will find something for performance --- Lists.partition(A, n).parallelStream().forEach({ //do stuff with temp }); – Ashraff Ali Wahab Nov 02 '22 at 18:32
  • 1
    Unless all lists returned by `e.getPersons()` have the same predictable size, there is not much you can do better. You can use `new ArrayList<>(LIMIT)` to initialize the list with the known required capacity. Using streams can’t provide any advantage as long as your `processIds` method requires a `List`. – Holger Nov 03 '22 at 15:48
  • What is the identifier e on the third line? – Brian Schack Nov 06 '22 at 19:18
  • @BrianSchack: Typo. Fixed – Jim Nov 06 '22 at 22:19

0 Answers0