简体   繁体   中英

Sorting based on string java

I have a list of objects that I need to sort based on a string .

each object in list would contain the below

e.g.
fruitType = Pear
fruitType = Mango
fruitType = Apple
fruitType = Apple
fruitType = Mango

Now, say i want to order by ' Apple ' first and then by ' Mango '. So apple comes on top first followed by mango.

I can do a normal sort asc/desc but that is not sufficient. Also is possible to use apache commons to do the above sort?

If you want to sort on a predefined order (ie, you've got some fixed ordering of strings in mind), then you could do it like this:

  1. Set up a HashMap<String,Integer> sortTable . Into it, you put all your strings, and map each one to its index in the sort order. If you want Apple first, then Mango , then Plum , etc., then you add these: sortTable.put("Apple",0); sortTable.put("Mango",1); sortTable.put("Plum",2); sortTable.put("Apple",0); sortTable.put("Mango",1); sortTable.put("Plum",2); and so on.
  2. Now write your Comparator as follows. When you compare two String instances s and t , you look both up in your HashMap and compare them by the value they map to. So if you're comparing Apple and Plum , you look up Apple and find it maps to 0 ; you look up Plum and you find it maps to 2 ; and you then return Integer.compare(0,2) .

In other words, your Comparator uses:

public int compare(String x, String y) {
    return Integer.compare(sortTable.get(x), sortTable.get(y));
}

This will allow you to use Collections.sort on your list, passing it the Comparator you've created.

Note that you need either some policy to deal with String s that aren't in your predefined list, or some guarantee that that will never happen.

public class Fruit implements Comparable<Fruit> {
    private String whatYouWantToSortBy;
    ...
    public int compareTo(Fruit other) {
        return whatYouWantToSortBy.compareTo(other.whatYouWantToSortBy);
    }
}

To sort, use Collections.sort . Or you can just use a type of List that automatically sorts itself, like TreeSet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM