Search...
FAQs
Subscribe
Pie
FAQs
Recent topics
Flagged topics
Hot topics
Best topics
Search...
Search within OCPJP
Search Coderanch
Advance search
Google search
Register / Login
Post Reply
Bookmark Topic
Watch Topic
New Topic
programming forums
Java
Mobile
Certification
Databases
Caching
Books
Engineering
Micro Controllers
OS
Languages
Paradigms
IDEs
Build Tools
Frameworks
Application Servers
Open Source
This Site
Careers
Other
Pie Elite
all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Tim Cooke
Campbell Ritchie
paul wheaton
Jeanne Boyarsky
Ron McLeod
Sheriffs:
Paul Clapham
Devaka Cooray
Saloon Keepers:
Tim Holloway
Carey Brown
Piet Souris
Bartenders:
Forum:
Programmer Certification (OCPJP)
ArrayList sorting using Ccomparator
rakeshdec kumar
Greenhorn
Posts: 9
posted 13 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
ArrayList al=new ArrayList();
al.add("ram");
al.add("xyz");
al.add(11);
al.add(55);
al.add("25");
How to implement Comparator for this list to sort elements
Ravishanker kumar
Ranch Hand
Posts: 53
posted 13 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
Here you are using different type of objects(
String
,Integer) into list.
Please use generic for collection.In this particular case,you can use natural order for string as below,
List al=new ArrayList();
al.add("ram");
al.add("xyz");
al.add("11");
al.add("55");
al.add("25");
System.out.println("Before sorting:"+al);
Collections.sort(al);
System.out.println("After Sorting:"+al);
rakeshdec kumar
Greenhorn
Posts: 9
posted 13 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
how to sort different types of objects
Stephan van Hulst
Bartender
Posts: 15737
368
posted 13 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
You first need to decide how two different objects compare, before you can sort them. How do 11 and "abc" compare, for instance?
If you want lexicographical sorting, you can do something like this:
Comparator<Object> lexicographically = new Comparator<Object>() { public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } }; List<?> list = Arrays.asList("ram", "xyz", 11, 55, "25"); Collections.sort(list, lexicographically); System.out.println(list);
rakeshdec kumar
Greenhorn
Posts: 9
posted 13 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
thank you
reply
reply
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
sending a Collection from JSP to Servlet
List contents - number of occurrences ?
How do you avoid an ArrayList object from being modified, i.e. avoid adding and deleting its content
items are not displayed in c:forEach
readonly ArrayList
More...