I’ve got 2 Solutions:
#1 Solution (Multiple for each loops)
// entries will be sorted by your comparator NavigableMap<Date, List<GpsDTO>> map = new TreeMap<yourComparator>(); // if there is a list already, it will be used; otherwise, a new one will be created gpsDtoList.forEach(dto -> map.computeIfAbsent(dto.getEreigniszeit(), new ArrayList<>()) .add(dto)); // iterate the relevant lists to set the respective markers map.firstEntry().forEach(dto -> dto.setOldest()); if (map.size() > 1) { map.lastEntry().forEach(dto -> dto.setNeweset()); }
In my understand this is O(3n)
and this is
#2 Solution (single for loop)
Date youngestDate = null; Date oldestDate = null; Collections.sort(gpsDtoList, new Comparator<T>() { public int compare(T o1, T o2) { return -o1.getEreigniszeit().compareTo(o2.getEreigniszeit()); } }); if (gpsDtoList != null && gpsDtoList.size() > 1) { youngestDate = gpsDtoList.get(0).getEreigniszeit(); oldestDate = gpsDtoList.get(gpsDtoList.size() - 1).getEreigniszeit(); } and the actual setting logic if (youngestDate != null && oldestDate != null) { if (i == 0 || youngestDate.equals(gpsDtoList.get(i).getEreigniszeit())) { properties.put("markerStyle", LATEST); } else if (oldestDate.equals(gpsDtoList.get(i).getEreigniszeit())) { properties.put("markerStyle", OLDEST); } }
This one uses a count based for loop. Which should be O(n)
Question
What has the better performance here, I’d go with Solution 2, but is it really more performant?