Guaranteed linear-time latestVersion() 25/84425/4
authorJim Hahn <jrh3@att.com>
Sat, 6 Apr 2019 03:32:15 +0000 (23:32 -0400)
committerJim Hahn <jrh3@att.com>
Sat, 6 Apr 2019 12:00:39 +0000 (08:00 -0400)
This is a proposed revision of the latestVersion() method that's
guaranteed to be linear time.  Still makes use of the slick idea
of sorting the list so that items with the same name are adjacent
and in order by version.
Revised to use an array list, which is more like the original code.

Change-Id: If047d4d9630c426c6335f52cb7e5bdda7b6cc0a9
Issue-ID: POLICY-1542
Signed-off-by: Jim Hahn <jrh3@att.com>
models-base/src/main/java/org/onap/policy/models/base/PfObjectFilter.java

index 0fca00d..a7d8401 100644 (file)
@@ -59,26 +59,31 @@ public interface PfObjectFilter<T extends Comparable<T>> {
      * @return the filtered list
      */
     public default List<T> latestVersionFilter(final List<T> originalList) {
+        if (originalList.size() <= 1) {
+            return originalList;
+        }
+
         List<T> filteredList = new ArrayList<>(originalList);
         Collections.sort(filteredList);
 
-        List<T> filteredOutList = new ArrayList<>();
-
-        for (int i = 1; i < filteredList.size(); i++) {
+        int icur = 0;
+        for (int j = 1; j < filteredList.size(); j++) {
             // Get the current and last element
-            T thisElement = filteredList.get(i);
-            T lastElement = filteredList.get(i - 1);
+            T curElement = filteredList.get(icur);
+            T lastElement = filteredList.get(j);
 
-            // The list is sorted so if the last element name is the same as the current element name, the last element
-            // should be removed
-            if (((PfNameVersion)thisElement).getName().equals(((PfNameVersion)lastElement).getName())) {
-                filteredOutList.add(lastElement);
+            /*
+             * The list is sorted so if the last element name is the same as the current
+             * element name, the current element should be removed.
+             */
+            if (!((PfNameVersion)curElement).getName().equals(((PfNameVersion)lastElement).getName())) {
+                // have a new name - done comparing with the old "current"
+                ++icur;
             }
-        }
 
-        // We can now remove these elements
-        filteredList.removeAll(filteredOutList);
+            filteredList.set(icur, lastElement);
+        }
 
-        return filteredList;
+        return new ArrayList<>(filteredList.subList(0, icur + 1));
     }
 }