+ 4
How can I make an array list in alphabetical order?
I have an array list in a class that contains the main method, and I want to use Collection.sort (arrayName) way without I need to use another class or interfaces, is it possible? if not, how can I use .sort and I keep my array in the main method?
17 Respostas
+ 16
Code example:
https://code.sololearn.com/c5q0Y3U2176w/?ref=app
+ 11
You've got an ArrayList that holds customers, so you may write a Comparator for that type, something like:
Comparator<Customer> comp = new Comparator<Customer>() {
@Override
public int compare(Customer c1, Customer c2) {
return c1.getName ().compareTo(c2.getName ());
}
};
Collections.sort(myList, comp);
+ 10
You can use Collections.sort(myList) as you mentioned. This is a static method, so you don't need an object to call it. It sorts an ArrayList<String> in alphabetical ascending order by default.
+ 9
See this for explanations on Comparator:
https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html
+ 4
Some sorting algorithms encase you're interested:
* Selection sort
* Insertion sort
* Quick sort
* Merge sort
* Tim sort
* bubble sort
* shell sort
+ 4
@Sooso Sweet ... sorry to intrude....
Can you break your problem down into a task that fits in CodePlayground?
...This is just like a StackExchange "smallest sample case" request except we get a bonus:
Then we can run your code here (at your profile) and people can directly benefit from the solution.
+ 3
my question is in Java not php *.* ! but thank you
+ 3
@Kirk Schafer sorry I don't know how to make codes in codePlayground :( but no problem for now I think the problem is solved but I got another problem now 😭 I will try find the solution
@Rrestoring faith yes I have used her code, thanks to her and you! 😊
+ 3
@Sooso No sorry about my comment I actually thought you were Kirk for a sec asking Tashi to post the code haha. Got confused, my bad.
+ 2
use bubble sorting algorithm
compare the adjacent string values using string 1.compareTo(string2)
+ 1
Great demonstration Tashi N
+ 1
hmm, I think I got it, I will try now 💖
+ 1
@Tashi N can I have a way to contact you? :( I want to invite you inside my computer so you can see my work and tell me best way to sort my array alphabetically without I change a lot of things, Thank you so much
+ 1
Am easy way is to import collections class and use the sort method
example: Collections.sort(object);
or else you can use your own sorting algorithm
0
@Tashi N look what happens when I try to do it :(
https://m.imgur.com/a/BHGov
and thank you so much for helping me ❤
I hope you know what is the problem
0
hmm sorry I couldn't understand it :(
is Comparator something like Arraylist? and why you have used Override ?
0
Use the sort method which is present in Collections class.
example:
consider you have created an Arraylist as 'al'.
and you've added all the elements in improper order .so if you want all the elements in order
use Collections.sort(al);.