Wednesday, March 25, 2015

Sort a set of strings by each string's last character, solution using comparator (Update)

I have the following problem. Sort a set of strings by each string's last character. This is my implementation, please suggest other solutions.

UPDATE
turns out I had a bug in my previous version, I was only comparing the last character to last character and on the return from the method, it would ignore every other word with same last character. It was only noticeable after a much larger sample set.



 package com.ervits;  
 import java.util.Comparator;  
 import java.util.Objects;  
 /**  
  *  
  * @author Artem  
  * @created Mar 27, 2015 2:07:21 PM  
  *  
  * Project SetSorter  
  *  
  */  
 class LastCharComparator implements Comparator {  
   public LastCharComparator() {  
   }  
   @Override  
   public int compare(String t1, String t2) {  
     Objects.requireNonNull(t1, "passed String1 cannot be null");  
     Objects.requireNonNull(t2, "passed String2 cannot be null");  
     final int result;  
     if(reverseWithStringBuilder(t1)  
         .compareTo(reverseWithStringBuilder(t2)) > 0) {  
       result = 1;  
     } else if (reverseWithStringBuilder(t1)  
         .compareTo(reverseWithStringBuilder(t2)) < 0) {  
       result = -1;  
     } else {  
       result = 0;  
     }  
     return result;  
   }  
   static String reverseWithStringBuilder(String aStr) {  
     return new StringBuilder(aStr).reverse().toString();  
   }  
 }  
 package com.ervits;  
 import java.util.Arrays;  
 import java.util.Comparator;  
 import java.util.LinkedHashSet;  
 import java.util.Set;  
 import java.util.SortedSet;  
 import java.util.TreeSet;  
 /**  
  *  
  * @author artem  
  */  
 public class SetSorter {  
   public static void main(String[] args) {  
     Set unsorted = new LinkedHashSet<>();  
     unsorted.addAll(Arrays.asList("xxxxxX", "xxxxxY", "hell7oD", "hel1loB", "helloC", "helloA", "helloE", "helloA", "helloZ"));  
     Comparator setComparator = new LastCharComparator();  
     SortedSet sorted = new TreeSet<>(setComparator);  
     sorted.addAll(unsorted);  
     System.out.println("***** UNSORTED *****");  
     System.out.println(unsorted.toString());  
     System.out.println("***** SORTED *****");  
     System.out.println(sorted.toString());  
     System.out.println("***** COMPARATOR *****");  
     System.out.println(sorted.comparator().getClass().getCanonicalName());  
   }  
 }  
Post a Comment