[英]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: 如果要按预定义的顺序排序(即,您已经牢记了一些固定的字符串顺序),则可以这样进行:
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. 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. 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
实例s
和t
,您都在HashMap
进行查找,并通过它们映射到的值进行比较。 So if you're comparing Apple
and Plum
, you look up Apple
and find it maps to 0
; Apple
和Plum
,则需要查找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.