Java sort by desired String

PaPaB1nG0 :

I am new to the idea of comparators and I am looking into ways to sort strings. In my code, below, I have made a list and sorted through it using the Collections.sort() method. Here is the code:

public class ComparatorTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        List<String> list = new ArrayList<String>();
        list.addAll(Arrays.asList("Bob Stone", "Jordan Brand", "Bob Mass", "Dylan Walsh","Tom Mavis","Bob Ganley"));
        System.out.println("Before sort "+ list);
        Collections.sort(list);
        System.out.println("After sort "+ list);
    }



}

How can I modify this to sort using a given String to sort by, instead of just sorting alphabetically? For example, if I give the string BOBthen all the BOB's will move to the front of the list. I did ask a sorting question before but I misunderstood the idea of sorting and it was more of a filtering question (java sort list of strings by string value entered by a user). This question is different from my earlier question because now I am trying to actually sort and rearrange the Strings instead of filtering them.

MadProgrammer :

The first thing you need to do is understand the rules, for example, what happens when:

  • Both the left hand side and right hand side start with "Bob"?
  • What happens when neither the left hand side and right hand side start with "Bob"?
  • Do you care about matching the case?
  • Do you only care about first names or should you included the surname or do you want that to be configurable?

A simple implementation might look something like...

public class NameComparator implements Comparator<String> {

    private String name;

    public NameComparator(String name) {
        this.name = name;
    }

    @Override
    public int compare(String lhs, String rhs) {
        if (lhs.startsWith(name) && rhs.startsWith(name)) {
            return lhs.compareTo(rhs);
        } else if (lhs.startsWith(name)) {
            return -1;
        } else if (lhs.startsWith(name)) {
            return 1;
        }

        return lhs.compareTo(rhs);
    }
}

Now, this does a case match (so bob is not the same as Bob) and will sub-sort all the "Bobs" within their own group

As you see, five seconds of thinking has brought up a lot of possible ways to sort the list, so you need to be aware of your options, which ones you might want to be customisable and which ones you want to be fixed.

You can call this example using something like...

Collections.sort(list, new NameComparator("Bob"));

Which will, based on your available input, output...

Before sort [Bob Stone, Jordan Brand, Bob Mass, Dylan Walsh, Tom Mavis, Bob Ganley]
After sort [Bob Ganley, Bob Mass, Bob Stone, Dylan Walsh, Jordan Brand, Tom Mavis]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=164721&siteId=1