Question about simplifying code related to loop iteration

jun shen :

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

jun shen :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=357372&siteId=1