You are on page 1of 9

http://www.albeesonline.

com/blog/2008/10/16/sorting-an-arraylist-of-objects/

class Person {
private String firstName;
private String lastName;
 
public Person(){
}
public Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
 
/**
* @return Returns the firstName.
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName The firstName to set.
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return Returns the lastName.
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName The lastName to set.
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
 
public String toString(){
return "## Firstname : "+this.firstName+", Lastname :
"+this.lastName;
}
}

I have created some objects of Person class and they are added to an ArrayList. Now I
need to sort the ArrayList based on Person’s firstName. The complete code listing for
sorting the ArrayList is given below.

Person p = new Person("Bruce", "Willis");


Person p1 = new Person("Tom", "Hanks");
Person p2 = new Person("Nicolas","Cage");
Person p3 = new Person("John","Travolta");
 
ArrayList list = new ArrayList();
list.add(p);
list.add(p1);
list.add(p2);
list.add(p3);
 
Collections.sort(list, new Comparator(){
 
public int compare(Object o1, Object o2) {
Person p1 = (Person) o1;
Person p2 = (Person) o2;
return
p1.getFirstName().compareToIgnoreCase(p2.getFirstName());
}
 
});
 
System.out.println(list);

http://www.indiastudychannel.com/resources/62136-Sort-an-ArrayList-Uisng-
Comparator.aspx

public static void sortAnyList(){


ArrayList aList = new ArrayList();
aList.add("Danny");
aList.add("Maddy");
aList.add("Rahul");
aList.add("Nilesh");
aList.add("Pranjna");
aList.add("Rohit");
Collections.sort(aList, new Comparator()
{
public int compare(Object o1, Object o2)
{
String s1 = (String)o1;
String s2 = (String)o2;
return s1.compareTo(s2);
}
});
}

http://www.javamex.com/tutorials/collections/sorting_comparator_example.shtml

public class StringLengthComparator implements Comparator<String> {


public int compare(String o1, String o2) {
if (o1.length() < o2.length()) {
return -1;
} else if (o1.length() > o2.length()) {
return 1;
} else {
return 0;
}
}
}

Now, armed with our Comparator and some vital string data that we need
ordering by length:
String[] strs = {"boxer shorts", "grundies", "boxers",
"elasticated Y-fronts", "underpants", "briefs"};

we can sort our string data by length with a simple call to Arrays.sort(), this
time passing in an instance of our parameter:

// Sort
Arrays.sort(strs, new StringLengthComparator());
// Print the results
for (String s : strs)
System.out.println(s);

http://www.coderanch.com/t/379475/java/java/Sorting-ArrayList

1. import java.util.*;   
2.     
3. public class Test {   
4.     
5.    public static void main(String[] args) {   
6.       ArrayList list = new ArrayList();   
7.     
8.       list.add("A");   
9.       list.add("H");   
10.       list.add("L1");   
11.       list.add("L100");   
12.       list.add("L11");   
13.       list.add("L2");   
14.       list.add("L3");   
15.       list.add("X");   
16.     
17.       class MyComparator implements Comparator {   
18.             
19.          public int compare(Object o1,   
20.                             Object o2) {   
21.             String s1 = o1.toString();   
22.             String s2 = o2.toString();   
23.     
24.             int counter = 0;   
25.     
26.             for (counter=0;counter<s1.length() &&   
27.                                !
Character.isDigit(s1.charAt(counter));counter++);   
28.     
29.             String temp1 = s1.substring(counter);   
30.     
31.             s1 = s1.substring(0,counter);   
32.     
33.             for (counter=0;counter<s2.length() &&   
34.                            !
Character.isDigit(s2.charAt(counter));counter++);   
35.     
36.             String temp2 = s2.substring(counter);   
37.     
38.             s2 = s2.substring(0,counter);   
39.     
40.             int max = (temp1.length() > temp2.length()) ? temp1.length() 
: temp2.length();   
41.     
42.             char[] pad = new char[max-temp1.length()];   
43.     
44.             Arrays.fill(pad,(char)48);   
45.     
46.             temp1 = String.valueOf(pad) + temp1;   
47.     
48.             pad = new char[max-temp2.length()];   
49.     
50.             Arrays.fill(pad,(char)48);   
51.     
52.             temp2 = String.valueOf(pad) + temp2;   
53.     
54.             s1 = s1 + temp1;   
55.             s2 = s2 + temp2;   
56.     
57.             return(s1.compareTo(s2));   
58.          }   
59.     
60.          public boolean equals(Object o1,   
61.                                Object o2) {   
62.             String s1 = o1.toString();   
63.             String s2 = o2.toString();   
64.     
65.             return(s1.equals(s2));   
66.          }   
67.     
68.       }   
69.     
70.       Collections.sort(list,new MyComparator());   
71.     
72.       Iterator iterator = list.iterator();   
73.     
74.       while (iterator.hasNext())   
75.          System.out.println(iterator.next());     
76.    }   
77.     
78. }

http://www.java-examples.com/sort-elements-java-arraylist-example

1. /*
2.   Sort elements of Java ArrayList Example
3.   This Java Example shows how to sort the elements of java ArrayList
object using
4.   Collections.sort method.
5. */
6.  
7. import java.util.ArrayList;
8. import java.util.Collections;
9.  
10. public class SortJavaArrayListExample {
11.  
12. public static void main(String[] args) {
13.  
14. //create an ArrayList object
15. ArrayList arrayList = new ArrayList();
16.  
17. //Add elements to Arraylist
18. arrayList.add("1");
19. arrayList.add("3");
20. arrayList.add("5");
21. arrayList.add("2");
22. arrayList.add("4");
23.  
24. /*
25.   To sort an ArrayList object, use Collection.sort method. This is
a
26.   static method. It sorts an ArrayList object's elements into
ascending order.
27.   */
28. Collections.sort(arrayList);
29.  
30. //display elements of ArrayList
31. System.out.println("ArrayList elements after sorting in ascending
order : ");
32. for(int i=0; i<arrayList.size(); i++)
33. System.out.println(arrayList.get(i));
34.  
35. }
36. }
37.  
38. /*
39. Output would be
40. ArrayList elements after sorting in ascending order :
41. 1
42. 2
43. 3
44. 4
45. 5
46. */

HashMap sort

Method 1
1. HashMap map = new HashMap();
2. map.put("0201", "0201");
3. map.put("01", "01");
4. map.put("0304", "0304");
5. map.put("0101", "0101");
6.  
7. Object[] key = map.keySet().toArray();
8. Arrays.sort(key);
9.  
10. for (int i = 0; i < key.length; i++)
{
11. System.out.println(map.get(key[i]));
12. }

Method 2

public HashMap getSortedMap(HashMap hmap)


{
HashMap map = new LinkedHashMap();
List mapKeys = new ArrayList(hmap.keySet());
List mapValues = new ArrayList(hmap.values());
hmap.clear();
TreeSet sortedSet = new TreeSet(mapValues);
Object[] sortedArray = sortedSet.toArray();
int size = sortedArray.length;
// a) Ascending sort

for (int i=0; i<size; i++)


{

map.put(mapKeys.get(mapValues.indexOf(sortedArray[i])), sortedArray[i]);

}
return map;
}

Method 3

static Map sortByValue(Map map) { 

     List list = new LinkedList(map.entrySet()); 

     Collections.sort(list, new Comparator() { 

          public int compare(Object o1, Object o2) { 

               return ((Comparable) ((Map.Entry) (o1)).getValue()) 

              .compareTo(((Map.Entry) (o2)).getValue()); 

          } 

     }); 

// logger.info(list); 

Map result = new LinkedHashMap(); 

for (Iterator it = list.iterator(); it.hasNext();) { 

     Map.Entry entry = (Map.Entry)it.next(); 

     result.put(entry.getKey(), entry.getValue()); 

     } 

return result; 

Method 4

public LinkedHashMap sortHashMapByValuesD(HashMap passedMap) {


List mapKeys = new ArrayList(passedMap.keySet());

List mapValues = new ArrayList(passedMap.values());

Collections.sort(mapValues);

Collections.sort(mapKeys);

LinkedHashMap sortedMap =

new LinkedHashMap();

Iterator valueIt = mapValues.iterator();

while (valueIt.hasNext()) {

Object val = valueIt.next();

Iterator keyIt = mapKeys.iterator();

while (keyIt.hasNext()) {

Object key = keyIt.next();

String comp1 = passedMap.get(key).toString();

String comp2 = val.toString();

if (comp1.equals(comp2)){

passedMap.remove(key);

mapKeys.remove(key);

sortedMap.put((String)key, (Double)val);

break;

return sortedMap;

Method 5:
HashMap based on values :
HashMap map1 = new HashMap();
map1.put("cat",5);
map1.put("cow",4);
map1.put("dog",3);
map1.put("horse",2);

List mpKeys = new ArrayList(map1.keySet());


List mpValues = new ArrayList(map1.values());

HashMap map = new LinkedHashMap();


TreeSet sortedSet = new TreeSet(mpValues);
Object[] sortedArray = sortedSet.toArray();
int size = sortedArray.length;
// descending

for (int i=size-1; i>=0; i--)


System.out.println(mpKeys.get(mpValues.indexOf(sortedArray[i]))+"
"+sortedArray[i]);

Based on Key:

Map myMap = new HashMap();


// put keys and values........
Map sortedMap = new TreeMap(myMap);

Method 6

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class Main {


public static void main(String[] args) {
HashMap callList = new HashMap();
callList.put("java", "pavan");
callList.put("makes", "srinivas");
callList.put("life", "sample");
callList.put("easy", "java");

Set set=callList.keySet();
String[] keys=new String[set.size()];
set.toArray(keys);
List tmpkeyList=Arrays.asList(keys);

Collections.sort(tmpkeyList);
for(String key:tmpkeyList){
System.out.println(key+":"+callList.get(key));
}
}
}
Method 7

sort based on the keys


Map yourMap= new HashMap();
// put some tuples in yourMap ...
Map sortedMap = new TreeMap(yourMap);

Sort based on the values


HashMap yourMap = new HashMap();
// put some tuples in yourMap ...
 
// to hold the result
HashMap map = new LinkedHashMap();
 
 
List yourMapKeys = new ArrayList(yourMap.keySet());
List yourMapValues = new ArrayList(yourMap.values());
TreeSet sortedSet = new TreeSet(yourMapValues);
Object[] sortedArray = sortedSet.toArray();
int size = sortedArray.length;
 
for (int i=0; i<size; i++) {
map.put
(yourMapKeys.get(yourMapValues.indexOf(sortedArray[i])),
sortedArray[i]);
}

To iterate your new Sorted Map


Set ref = map.keySet();
Iterator it = ref.iterator();
 
while (it.hasNext()) {
String file = (String)it.next();
}

You might also like