Search code examples
javacoding-style

Question about simplifying code related to loop iteration


I have a question on coding. I get a task which is to iterate a list of elements to do dedupe.

The list of elements are ordered by time and are divided into sub time windows. In each sub time window, I need to pick up the deduplicated element per some business logic. Per the business logic, the deduplicated element in a sub time window is only known when all elements in the sub time window are iterated. My question is how to simplify coding for this task.

The best I can think of is some pseudo-code like below

List<Element> deduplicated = new List();
Element subWindowPeekSignal = null;
Time subWindowEndTime = null;

elements.foreach(e -> {
      if (subWindowPeekElement != null
           && subWindowEndTime != null
           && isElementInTimeWindow(e, subWindowEndTime) {
         if (isIteratedElementHigherPriority(subWindowPeekElement, e)) {
             subWindowPeekElement = e;
         }
      } else {
         if (subWindowPeekElement != null) {
            deduplicated.add(subWindowPeekElement);
         }
         subWindowPeekElement = e;
         subWindowEndTime = getTime(e);
      }
  });

  //the ugly statement outside of loop
  deduplicated.add(subWindowPeekElement);

Specifically, how to avoid the last statement outside of the loop? Is it possible to finish the task of collecting all deduplicated elements within a loop or a use of java stream?

Many thanks, Jun


Solution

  • This is the best solution, per discussion in my team.