?
Solved

Sorting numbers and letters using Comparator with Collections.sort

Posted on 2009-12-17
5
Medium Priority
?
650 Views
Last Modified: 2013-12-22
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
Comment
Question by:kineticexpert
5 Comments
 
LVL 92

Accepted Solution

by:
objects earned 2000 total points
ID: 26077358
>         Collections.sort(myArrayList, new StringNumberComparator());

>     static class MyComparator implements Comparator

thats not the comparator being used
0
 
LVL 92

Expert Comment

by:objects
ID: 26077362
the comparator you have posted never actually compares the keys, only the values
0
 
LVL 20

Expert Comment

by:a_b
ID: 26077674
Change -   Collections.sort(myArrayList, new MyComparator());
0
 

Author Comment

by:kineticexpert
ID: 26093417
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
 
LVL 8

Expert Comment

by:Santhana
ID: 26283170
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

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month15 days, 4 hours left to enroll

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question