I think this may be a duplicate question. But couldn't find the answer for my requirement.
I have a list of names (String) such as
Merill, Gopi, kamal, orange, white
I need to do something to get the list in ascending order using collections like the following
Gopi, kamal, Merill, orange, white
Is it possible to get the list in alphabeticalorder?
Can anyone please tell how to sort this using collections?
(Please provide a solution before closing this questiona as duplicate)
You can use this:
Collections.sort(list, String.CASE_INSENSITIVE_ORDER)
String.CASE_INSENSITIVE_ORDER
is a Comparator<String>
in String
class. Note that this is not locale-aware.
You've already mentioned the solution in your post:
Can anyone please tell how to sort this using collectins?
Use java.util.Collections.sort(...)
.
Collections.sort(pass the list) will soft in ascending order. If you want to sort your own way then you need to use Comparator but here there is no need of doing that.
I know your trying to sort it using Collections, but here's a simple way:
public static void main(String[] args) throws ParseException {
String[] values = new String[] {"Some item", "another item", "1 last more", "nevermind", "this is different"};
System.out.println("Before: " + Arrays.toString(values));
Arrays.sort(values, new Comparator<String>() {
@Override
public int compare(String arg0, String arg1) {
return arg0.compareTo(arg1);
}
});
System.out.println("After: " + Arrays.toString(values));
}
And this is outputted:
Before: [Some item, another item, 1 last more, nevermind, this is different]
After: [1 last more, Some item, another item, nevermind, this is different]
The array is sorted numerical/other first, then capital-alphabetical, then lowercase-alphabetical
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.