criskgl
10/6/2019 - 5:27 PM

Number and letter Logs

NUMBER AND LETTER LOGS

We receive either letter logs

  • Letter-logs come before digit-logs;
  • Letter-logs are sorted alphanumerically, by content then identifier;
  • Digit-logs remain in the same order.

OUR LAMBDA EXPRESSION ASSUMES THAT IT WILL BE RECEIVING TWO THINGS EACH TIME, WE JUST SAY THEY ARE o1 & o2 and treat them to compare them.

We are just building a comparator.

Here is a more detailed explanation of what we are doing:

public String[] reorderLogFiles(String[] logs) {
  if (logs == null || logs.length == 0) return logs;
  int len = logs.length;
  List<String> letterList = new ArrayList<>();
  List<String> digitList = new ArrayList<>();
  for (String log : logs) {
    if (log.split(" ")[1].charAt(0) < 'a') {
        digitList.add(log);
    } else {
        letterList.add(log);
    }
  }
  /********************************************** 
  *  MOST IMPORTANT PART DOWN HERE USING LAMBDA *
  *  EXPRESSIONS AS THE COMPARATOR              *
  ***********************************************/
  Collections.sort(letterList, (o1, o2) -> {
    //the sorting will take two objects 
    //o1 & o2 which will be Strings from letterList,
    //which contains all the letterLogs
      String[] s1 = o1.split(" ");
      String[] s2 = o2.split(" ");
      int len1 = s1.length;
      int len2 = s2.length;
      for (int i = 1; i < Math.min(len1, len2); i++) {//only go up to as many word as the min length
          if (!s1[i].equals(s2[i])) {
              return s1[i].compareTo(s2[i]);
          }
          //if equal go to next one
      }
      //tie --> use identifier to compare 
      return s1[0].compareTo(s2[0]);
  });
  //BUILD FINAL RESULT
  for (int i = 0; i < len; i++) {
      if (i < letterList.size())
          logs[i] = letterList.get(i);
      else logs[i] = digitList.get(i - letterList.size());
  }
  return logs;
}