Sorting numbers and letters using Comparator with Collections.sort

Posted on 2009-12-17
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;




            Map.Entry e=(Map.Entry);

            key = (String)e.getKey();

            value = ((String)e.getValue()).toString();

            System.out.println("Value = " + value + "                         Key: " + key);




    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();


            String word1=(String)e1.getKey();

            String word2=(String)e2.getKey();


        } 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

Question by:kineticexpert
    LVL 92

    Accepted Solution

    >         Collections.sort(myArrayList, new StringNumberComparator());

    >     static class MyComparator implements Comparator

    thats not the comparator being used
    LVL 92

    Expert Comment

    the comparator you have posted never actually compares the keys, only the values
    LVL 20

    Expert Comment

    Change -   Collections.sort(myArrayList, new MyComparator());

    Author Comment

    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 <> 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
    // 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;
             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;
          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)
                return new BigInteger(str1).compareTo(new BigInteger(str2));
             catch (NumberFormatException ex)
                return 0;
          return str1.compareTo(str2);

    Open in new window

    LVL 8

    Expert Comment

         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.....


    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Join & Write a Comment

    Suggested Solutions

    By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
    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…
    Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
    This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

    754 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

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now