Search code examples
javastringcomparatorcomparable

Sort String s2 using the order of String s1 using either of comparable or comparator interface


i have two strings s1 and s2 and i would like to sort s2 based on the order of appearance of letters in s1 and if other alphabets are left in s2 sort them alphabetically.

Assume i have the following;

String s1 = "war";

String s2 = "Its awesome being a programmer";

output: waaarrrIbeeeeggimmmnoopsst.

I have written a code to do that already though buut i was wondering if its possible using the comparator/comparable interface to solve it.

Listed below is my code snippet.

public class Sort {

    private static String a = "war";
    private static String b = "Its awesome being a programmer";
    static List<Character> list = new ArrayList<>();

    static public void main(String[] args) {
        Character s;
        Character x;

        System.out.println("String to be sorted: '" + b + "'");
        System.out.println("Key for sort: '" + a + "'");

        /* 
         * put all the string in a list 
         */
        for (int i = 0; i < b.length(); i++) {
            s = b.charAt(i);
            if (s != ' ') {
                list.add(s);
            }
        }
        /* 
         * compare individual chac in key with individaul char in string to sort 
         */
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < a.length(); j++) {
            x = a.charAt(j);
            for (int k = 0; k < b.length(); k++) {
                s = b.charAt(k);
                if (x == s) {
                    sb.append(s);
                    list.remove(x);
                }
            }
        }

        /* 
         * check if list is empty if not, sort and append the rest to the stringbuilder 
         */
        if (!list.isEmpty()) {
            Collections.sort(list);
            for (char c : list) {
                sb.append(c);
            }
        }
        System.out.println("Sorted version of string: '" + sb.toString() + "'");
    }
}

Solution

  • private static String a = "war";
    private static String b = "Its awesome being a programmer".replace(" ","");
    private static String answer = "waaarrrIbeeeeggimmmnoopsst";
    
    public static void main(String[] args) {
        List<String> characters = new ArrayList<String>(b.length());
        for (int i=0;i<b.length();i++){
            characters.add(String.valueOf(b.charAt(i)));
        }
        Collections.sort(characters,new CompareIt(a));
        String sortedString = listToString(characters);
        System.out.println(sortedString);
        System.out.println(answer);
        System.out.println(answer.equals(sortedString));
    }
    private static String listToString(List<String> listOfStrings){
        StringBuilder builder = new StringBuilder();
        for (String str : listOfStrings){
            builder.append(str);
        }
        return builder.toString();
    }
    private static class CompareIt implements Comparator<String>{
    
        private final String source;
    
        public CompareIt(String source) {
            super();
            this.source = source;
        }
    
        public int compare(String o1, String o2) {
            int i1 = source.indexOf(o1);
            int i2 = source.indexOf(o2);
            if (i1==-1 && i2!=-1){
                return 1;
            } else if (i1!=-1 && i2==-1){
                return -1;
            } else if (i1!=-1 && i2!=-1){
                return i1 > i2 ? 1:-1;
            } else {
                return o1.compareTo(o2);
            }
        }
    
    }
    

    This seems to work. EDITED: To include sysout that result matches expected answer provided in question. EDIT2: Typo with final indexed comparison I had ? 1:0 instead of 1:-1.