简体   繁体   English

基于字符串Java排序

[英]Sorting based on string java

I have a list of objects that I need to sort based on a string . 我有一个需要基于string排序的对象list

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 '. 现在,说我想先按“ Apple ”订购,然后按“ Mango ”订购。 So apple comes on top first followed by mango. 因此,苹果排在第一位,其次是芒果。

I can do a normal sort asc/desc but that is not sufficient. 我可以做一个普通的asc / desc排序,但这还不够。 Also is possible to use apache commons to do the above sort? 也可以使用apache commons进行上述排序吗?

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 . 设置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); 如果您首先要使用Apple ,然后是Mango ,然后是Plum等,则添加以下内容: 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. 现在,按如下所示编写Comparator 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. 比较两个String实例st ,您都在HashMap进行查找,并通过它们映射到的值进行比较。 So if you're comparing Apple and Plum , you look up Apple and find it maps to 0 ; 因此,如果您要比较ApplePlum ,则需要查找Apple并发现它映射为0 you look up Plum and you find it maps to 2 ; 您查找Plum ,发现它映射到2 and you then return Integer.compare(0,2) . 然后return Integer.compare(0,2)

In other words, your Comparator uses: 换句话说,您的Comparator使用:

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. 这样,您就可以在列表中使用Collections.sort ,并将您创建的Comparator传递给它。

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. 注意,您需要某种策略来处理未在预定义列表中的String ,或者需要某种保证永远不会发生的策略。

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

To sort, use Collections.sort . 要排序,请使用Collections.sort Or you can just use a type of List that automatically sorts itself, like TreeSet. 或者,您可以只使用一种自动对自身进行排序的List类型,例如TreeSet。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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