0

I have a string Set with a set of strings which is a combination of timestamp a recordid.

How do I create a new string Set in a neat way with only the records with the latest timestamps

Example:

set<keyString> recString = {rec_20200123101351-00T2o000000B5QxXXXX.txt, rec_20200123101351-00T2o000000B5QxXXXX.txt, rec_20200123111034-00T2o000000B7aAAAA.txt}

This should become

set<keyString> recString = {rec_20200123101351-00T2o000000B5QxXXXX.txt, rec_20200123111034-00T2o000000B7aAAAA.txt}
1

You might try creating a Map with key of record id and value of set string. So as you loop through the first set, you'd substring out the record id and check the map for that key. If it exists, you then substring out the timestamps and compare them. If the value from the set is newer than what's already in the map, replace it, else keep what's already in the map. If the key doesn't exist, that's your newest timestamp for the record so go ahead and put it in.

The below isn't completely valid code but might give you an idea what I mean.

Map<String, String> newestVals = new Map<String, String>();
for (String val : stringSet) {
  String id = val.substring(val.indexOf('-'), val.indexOf('.'));

  if (newestVals.containsKey(id)) {
    String existingVal = newestVals.get(id);
    String existingStamp = existingVal.substring(existingVal.indexOf('_'), existingVal.indexOf('-'));
    String setStamp = val.substring(existingVal.indexOf('_'), val.indexOf('-')); 
    if (setStamp > existingStamp) { // this won't work as it's string compare, convert to dates and compare
      newestVals.put(id, val);
    }
  } else {
    newestVals.put(id, val);
  }
}
| improve this answer | |
  • This seems like a solution if I do integer.valueof(setStamp) > integer.valueof(existingStamp). I will test this and If so mark as correct answer. Thx! – Thomas Jan 23 at 11:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.