Friday, March 26, 2010

Array List Sorting Issue

Hi,

Recently, i was coding for an application and came across a problem where i need to sort an ArrayList in an alphabetical order. However, that sounded quite easy as because sorting can easy with single arraylist. But, i was in a situation where i had two different ArrayLists with multiple attributes. So, what i did is that i kept a delimeter to distinct all my 3 values and then i added them into a temporary list.


for(int j=0;j
{
myBean=(MyBean)myList.get(j);
tempList.add(myBean.getOne() + "*" + myBean.getTwo() + "*" + myBean.getThree());

then i used collection's sort method to sort them up in an alphabetical form.

Collections.sort(tempList,new MyComparator());  


I used inner class called Mycomparator to compare.


 class MyComparator implements Comparator {   
         
         public int compare(Object o1,   
                            Object o2) {   
            String s1 = o1.toString().toUpperCase();   
            String s2 = o2.toString().toUpperCase();   
    
            int counter = 0;   
    
            for (counter=0;counter
                               !Character.isDigit(s1.charAt(counter));counter++);   
    
            String temp1 = s1.substring(counter);   
    
            s1 = s1.substring(0,counter);   
    
            for (counter=0;counter
                           !Character.isDigit(s2.charAt(counter));counter++);   
    
            String temp2 = s2.substring(counter);   
    
            s2 = s2.substring(0,counter);   
    
            int max = (temp1.length() > temp2.length()) ? temp1.length() : temp2.length();   
    
            char[] pad = new char[max-temp1.length()];   
    
            Arrays.fill(pad,(char)48);   
    
            temp1 = String.valueOf(pad) + temp1;   
    
            pad = new char[max-temp2.length()];   
    
            Arrays.fill(pad,(char)48);   
    
            temp2 = String.valueOf(pad) + temp2;   
    
            s1 = s1 + temp1;   
            s2 = s2 + temp2;   
    
            return(s1.compareTo(s2));   
         }   
    
         public boolean equals(Object o1,   
                               Object o2) {   
            String s1 = o1.toString();   
            String s2 = o2.toString();   
    
            return(s1.equals(s2));   
         }   
    
      }   


And finally,. the problem got resolved, i got my list ordered in alphabetical form.



No comments: