ITGeek
ITGeek

Reputation: 24

Given the List<String> need to sort it in given alphabetical order using stream and comparator

given list and set of letters to sort the list using java stream

List<String> names= Arrays.asList("Robin","Zax","John");
String order = "ZALBKNDWMTFCGOIUHEPQXSYVRJ"; 

EXAMPLE: Input: List names= Arrays.asList("Robin","Zax","John"); String order = "ZJR"

Output: ["Zax","John","Robin"]

Input 2: List<String> names= Arrays.asList("Robin","Zax","John","Rohan"); String order = "OZJRHBAS";

OUTPUT: ["Zax","John","Rohan","Robin"]

 names.stream().sorted(new MyComparator(order)).collect(Collectors.toList()).forEach(System.out::println); 

I just want the implementation of compare method below is what i have tried but its sorting on the basis of only first letter. Is there any way it can be done in such a way the all the letters of string are taken care for sorting.

class MyComparator implements Comparator<String> {
    private String order;

    MyComparator(String order) {
        this.order = order;
    }

    @Override
    public int compare(String s1, String s2) {
        char[] charsOfS1 = s1.toCharArray();
        char[] charsOfS2 = s2.toCharArray();
        int proximity = 0;
        for(int i=0; i<Math.min(charsOfS1.length,charsOfS2.length);i++){
            int check = order.indexOf(s1.charAt(i)) - order.indexOf((s2.charAt(i)));
            if(check<0)
                proximity--;
            else if(check>0)
                proximity++;
        }
        return proximity;
    }
}

Upvotes: 0

Views: 131

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79025

You can simply compare the index position of the first character of strings:

public int compare(String s1, String s2) {
    return order.indexOf(s1.charAt(0)) - order.indexOf((s2.charAt(0)));
}

Full Demo:

import java.util.Comparator;
import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;

class MyComparator implements Comparator<String> {
    private String order;

    MyComparator(String order) {
        this.order = order;
    }

    @Override
    public int compare(String s1, String s2) {
        return order.indexOf(s1.charAt(0)) - order.indexOf((s2.charAt(0)));
    }
}

public class Main {
    public static void main(String[] args) {
        // Test
        List<String> names = Arrays.asList("Robin", "Zax", "John");
        String order = "ZJR";
        System.out.println(names.stream().sorted(new MyComparator(order)).toList());
    }
}

Output:

[Zax, John, Robin]

Upvotes: 1

Related Questions