• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 667
  • Last Modified:

Sorting numbers and letters using Comparator with Collections.sort

I am trying to sort an ArrayList so that a list of values from a Hashtable are sorted by value, which includes numbers sorted in numerical order and before Characters.

Script below...

 
Hashtable danHT = new Hashtable();
        danHT.put("15", "15a");
        danHT.put("1", "1a");
        danHT.put("4", "da");
        danHT.put("7", "7a");
        danHT.put("77", "77a");
        danHT.put("2", "2a");
        danHT.put("737", "aaa");
        danHT.put("87", "AAA");
        danHT.put("11", "11a");
        danHT.put("23", "BB23");

        ArrayList myArrayList=new ArrayList(danHT.entrySet());
        Collections.sort(myArrayList, new StringNumberComparator());

        Iterator itr=myArrayList.iterator();
        String key="";
        String value="";
        int cnt=0;
        while(itr.hasNext())
        {
            cnt++;
            Map.Entry e=(Map.Entry)itr.next();
            key = (String)e.getKey();
            value = ((String)e.getValue()).toString();
            System.out.println("Value = " + value + "                         Key: " + key);
        }
     

and...

    static class MyComparator implements Comparator
    {
        public int compare(Object obj1, Object obj2)
        {
            int result=0;Map.Entry e1 = (Map.Entry)obj1 ;
            Map.Entry e2 = (Map.Entry)obj2 ;//Sort based on values.
            String value1 = (String)e1.getValue();
            String value2 = (String)e2.getValue();
            if(value1.compareTo(value2)==0){
            String word1=(String)e1.getKey();
            String word2=(String)e2.getKey();
            result=value1.compareToIgnoreCase(value2);
        } else {
                //Sort values in a descending order
                result=value2.compareTo( value1 );
            }
            return result;
        }
    }



However the Values that get sorted are..
Value = 1a                         Key: 1
Value = 2a                         Key: 2
Value = da                         Key: 4
Value = 7a                         Key: 7
Value = 11a                         Key: 11
Value = 15a                         Key: 15
Value = BB23                         Key: 23
Value = 77a                         Key: 77
Value = AAA                         Key: 87
Value = aaa                         Key: 737


It seems to have sorted based upon the Keys?? But I'm not sure why it would be doing this?

Open in new window

0
kineticexpert
Asked:
kineticexpert
1 Solution
 
objectsCommented:
>         Collections.sort(myArrayList, new StringNumberComparator());

>     static class MyComparator implements Comparator

thats not the comparator being used
0
 
objectsCommented:
the comparator you have posted never actually compares the keys, only the values
0
 
a_bCommented:
Change -   Collections.sort(myArrayList, new MyComparator());
0
 
kineticexpertAuthor Commented:
Oh yes, my mistake. I had tried a few different Comparators that I had found online. The StringNumber one is below..
// This file is
// (c) Copyright Bent Dalager <bcd@pvv.org> 2004 - 2005
// All rights reserved.
//
// The file may be distributed under the terms of the GNU General Public
// License version 2.
//
// A copy of that license should be included in the distribution where you
// found this file. It can also be found at
// http://www.gnu.org/licenses/gpl.txt
//
// If you are unable to locate the full text of the GNU General Public License
// version 2 then you may not assume any rights to this file beyond that
// afforded to you by relevant copyright legislation.

package code_list_sorting;

import java.math.BigInteger;


public class StringNumberComparator <T>
   implements java.util.Comparator <T>
{
   public StringNumberComparator()
   {
   }

   public int compare(T a, T b)
   {
      if (a == null && b == null) return 0;
      if (a == null) return -1;
      if (b == null) return 1;
      StringBuffer sba = new StringBuffer(a.toString());
      StringBuffer sbb = new StringBuffer(b.toString());
      if (sba.length() == 0 && sbb.length() == 0) return 0;
      if (sba.length() == 0) return -1;
      if (sbb.length() == 0) return 1;

      int offsa = 0;
      int lena = 0;
      int offsb = 0;
      int lenb = 0;
      int result;
      do
      {
         lena = calcLength(sba, offsa);
         lenb = calcLength(sbb, offsb);
         if ((result = compareRegions(sba, offsa, lena, sbb, offsb, lenb)) != 0)
         {
            return result;
         }
         offsa += lena;
         offsb += lenb;
      }
      while((offsa < sba.length()) && (offsb < sbb.length()));
      return new Integer(sba.length()).compareTo(new Integer(sbb.length()));
   }

   protected int calcLength(StringBuffer buff, int fromOffset)
   {
      boolean areDigits = Character.isDigit(buff.charAt(fromOffset));
      int retval = 0;
      do
      {
         ++retval;
      }
      while (
         fromOffset + retval < buff.length() &&
         Character.isDigit(buff.charAt(fromOffset + retval)) == areDigits);
      return retval;
   }

   protected int compareRegions(
      StringBuffer buff1,
      int offset1,
      int length1,
      StringBuffer buff2,
      int offset2,
      int length2)
   {
      boolean isDigit1 = Character.isDigit(buff1.charAt(offset1));
      boolean isDigit2 = Character.isDigit(buff2.charAt(offset1));
      if (isDigit1 != isDigit2)
      {
         return isDigit1 ? -1 : 1;
      }
      String str1 = buff1.substring(offset1, offset1 + length1);
      String str2 = buff2.substring(offset2, offset2 + length2);
      if (isDigit1)
      {
         try
         {
            return new BigInteger(str1).compareTo(new BigInteger(str2));
         }
         catch (NumberFormatException ex)
         {
            return 0;
         }
      }
      return str1.compareTo(str2);
   }

}

Open in new window

0
 
SanthanaTechnical LeadCommented:
hai.....
     First change your your code---Collections.sort(myArrayList, new MyComparator());
like this.......

Then here  ---> ArrayList myArrayList=new ArrayList(danHT.entrySet());  
If you make change like this....It will sort based upon values.....



solution.txt
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now