TreeSet vs Collection.Sort / Array.sort for Strings

Gurus
I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
Basically I have a list of Strings, i need to perform the following operations on these Strings
1) Able to list Strings starting with a Prefix
2) Able to list Strings Lexically greater than a String
Any help would be greatly appreciated!
Thanks a bunch

SpaceShuttle wrote:
Gurus
I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
Basically I have a list of Strings, i need to perform the following operations on these Strings
1) Able to list Strings starting with a Prefix
2) Able to list Strings Lexically greater than a String
Any help would be greatly appreciated!
Thanks a bunchBig-O wise, there's no difference between sorting a list of N elements or inserting them one by one in a tree-set. Both take O(n*log(n)). But both collections are not well suited for looking up string that start with a certain substring. In that case you had better use a Patricia tree (or Radix tree).
Good luck.

Similar Messages

  • Having probs with radix Sort for strings

    I am creating a method that does radix sort for string values. I think I need to know the maximum value for strings to do this, and I have no Idea what that would be

    As in the maximum size of a string?
    Do you mean characters or actual byte size?

  • Compile error when using Collections.sort for Vector, why?

    The compiler is giving an error when trying to do this (I'm using JDK 1.5.0_09):
    Vector <String> test = new Vector <String>();
    test.add("test1");
    test.add("test2");
    test.add("test3");
    Collections.sort(test);The error being:
    The method sort(Vector<String>) is undefined for the type Collections
    Collections.sort takes List, but Vector is of type List, so this should work, correct?

    ChuckBing wrote:
    No. Vector is not a subclass of List. Use List.um.. Vector implements List

  • Table Sorter for String displaying Numbers

    Hi All.
    I have a table whose one of the columns display numbers with data type string. This is becuase :
    1. RFC gives me as String.
    2. I have to display blank in case no value or zero is present (since int, long etc default to Zero, hence  
        not used).
    I have to sort this column as a number.Since the datatype is string, it sorts the numbers as string
    for example : if we have  values like : 2, 4, 3, 10, 19, 15, 20, 22
    currently as String it sorts as follows : 10, 15, 19, 2, 20, 22, 3, 4.
    but i want as follows : 2, 3, 4, 10, 15, 19, 20, 22.
    Useful answers will appreciated.
    Thanks and regards,
    Aditya Deshpande.

    In order to sort the node with attribute of type string; please use the following code..
    Here use the node where you store the string value..
    wdContext.nodeTest().sortElements(
                new Comparator() {
                   public int compare(Object o1, Object o2) {
                        // TODO Auto-generated method stub
                   IPrivateExperimentView.ITestElement ele1 = (IPrivateExperimentView.ITestElement)o1;
                   IPrivateExperimentView.ITestElement ele2 = (IPrivateExperimentView.ITestElement)o2;
                        return Integer.parseInt( ele1.getNumStr()) > Integer.parseInt( ele2.getNumStr()) ? 1 : -1;
    input :  "2", "4", "3", "10", "19", "15", "20", "22"
    result : "2", "3", "4", "10", "15", "19", "20", "22"
    vinod

  • Sorting for loop

    Hi all...
    I using for loop to display student information and i want to sort the information (e.g. module code, name, admin no and etc) given in ascending and descending order. I use combo box to list and select the (information) to be sorted in either in ascending or decending order.
    But, how sld i code in the way that the result will change instance whenever i click the combo box ( e.g name) to be sorted in ascending order. Cos now, it only sort the last index, last student information and not all the student.
    Below is what i have done:
    String [] headerString = {"Module Group", "Tutorial Group", "Admin No", "Name"};
    //Create combo box
    JComboBox header = new JComboBox(headerString);
    header.setSelectedIndex(3);
    header.addActionListener(this);
    //Create the radio buttons
    ascendButton = new JRadioButton("Ascending", true);
    ascendButton.setMnemonic(KeyEvent.VK_UP);
    ascendButton.setSelected(true);
    descendButton = new JRadioButton("Descending", false);
    descendButton.setMnemonic(KeyEvent.VK_DOWN);
    //Register a listener for the radio buttons.
    ascendButton.addActionListener(this);
    descendButton.addActionListener(this);
    //Group the radio buttons
    group = new ButtonGroup();
    group.add(ascendButton);
    group.add(descendButton);
    buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    buttonPanel.add(header);
    buttonPanel.add(ascendButton);
    buttonPanel.add(descendButton);
    class nameComparator implements Comparator
    public int compare(Object o1, Object o2)
    Vector one = (Vector)o1;
    Vector two = (Vector)o2;
    //the following line will return a negative value
    //if one is smaller in size than two
    //   return one - two;
    public boolean equals(Object obj)
    //don't know what to put it
    public void actionPerformed(ActionEvent event)
    System.out.println("Before" + v);
    if (ascendButton.isSelected())
    //Sort by natural order
    //Case-insensitive sort, ie. a, C, z
    Collections.sort(v, String.CASE_INSENSITIVE_ORDER);          
    else
    //Reverse-order sort
    Collections.sort(v, Collections.reverseOrder());
    list.setListData(v);
    //Reset the model used by the JComboBox after sorting the vector
    DefaultComboBoxModel model = new DefaultComboBoxModel(headerString);
    header.setModel(model);
    System.out.println("After" +  v);
    //reconstruct the vector and repaint again
    repaint();
    }

    Hi all, below is my coding. I still don't know how to start to sort my jlist. hope guys out there can give me some idea. Thanks.
    import java.awt.*;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import java.util.*;
    import java.util.Vector.*;
    public class Display extends JFrame implements ActionListener{
      JButton editButton;
      JButton setButton;
      JComboBox header;
      JLabel imageLabel;
      JLabel acadYrLabel;
      JLabel semseterLabel;
      JLabel moduleCodeLabel;
      JLabel moduleGroupLabel;
      JLabel tutorialGroupLabel;
      JLabel admNoLabel;
      JLabel nameLabel;
      JPanel aPanel;
      JPanel imagePanel;
      JPanel soloPanel;
      JPanel buttonPanel;
      JPanel contentPanel;
      JPanel textFieldPanel;
      JRadioButton ascendButton;
      JRadioButton descendButton;
      JScrollPane infoPane;
      JScrollPane scrollPane;
      JTextField textField;
      JTextField moduleGroupField;
      JTextField tutorialGroup;
      JTextField adminNo;
      JTextField nameField;
      JTextField acadYrField;
       String[] headerString = {
          "Module Group", "Tutorial Group", "Admin No", "Name"};
       public Display()
        //Create combo box
        header = new JComboBox(headerString);
        header.setSelectedIndex(3);
        header.addActionListener(this);
        //Create the radio buttons
        ascendButton = new JRadioButton("Ascending", true);
        ascendButton.setMnemonic(KeyEvent.VK_UP);
        ascendButton.setSelected(true);
        descendButton = new JRadioButton("Descending", false);
        descendButton.setMnemonic(KeyEvent.VK_DOWN);
        //Register a listener for the radio buttons.
        ascendButton.addActionListener(this);
        descendButton.addActionListener(this);
        //Group the radio buttons
        ButtonGroup group = new ButtonGroup();
        group.add(ascendButton);
        group.add(descendButton);
        buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        //buttonPanel.setAlwaysOnTop(true);
        buttonPanel.add(header);
        buttonPanel.add(ascendButton);
        buttonPanel.add(descendButton);
        imagePanel = new JPanel(new GridLayout(10, 3));
        imagePanel.addComponentListener(new ComponentAdapter()
          public void componentResized(ComponentEvent e)
            JPanel p = (JPanel) e.getComponent();
         populate(50,60);
    public void populate(int length, int height)
        for (int i = 0; i <30; i++)
          soloPanel = new JPanel(new BorderLayout(0, 20)); //Specified gaps between components
          soloPanel.setPreferredSize(new Dimension(length, height+150));
          soloPanel.setBackground(Color.GRAY);
          //Create the text field and set it up
          acadYrField = new JTextField();
          acadYrField.setBackground(Color.GRAY);
          acadYrField.setColumns(20);
          acadYrField.setEditable(false);
          acadYrField.setText("2004");
          tutorialGroup = new JTextField();
          tutorialGroup.setBackground(Color.GRAY);
          tutorialGroup.setColumns(20);
          tutorialGroup.setEditable(false);
           tutorialGroup.setText("BM0539"+i+i);
          adminNo = new JTextField();
          adminNo.setBackground(Color.GRAY);
          adminNo.setColumns(20);
          adminNo.setEditable(false);
          adminNo.setText("012345X" + i);
          moduleGroupField = new JTextField();
          moduleGroupField.setBackground(Color.GRAY);
          moduleGroupField.setColumns(20);
          moduleGroupField.setEditable(false);
          moduleGroupField.setText("IT12345");
          nameField = new JTextField();
          nameField.setBackground(Color.GRAY);
          nameField.setColumns(20);
          nameField.setEditable(false);
          nameField.setText("Alex" + i);
          textFieldPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
          textFieldPanel.setBackground(Color.GRAY);
          textFieldPanel.setPreferredSize(new Dimension(235, 180));
          textFieldPanel.add(acadYrField);
          textFieldPanel.add(tutorialGroup);
          textFieldPanel.add(adminNo);
          textFieldPanel.add(moduleGroupField);
          textFieldPanel.add(nameField);
        infoPane = new JScrollPane(textFieldPanel,
                                   JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                   JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        editButton = new JButton("Edit");
        editButton.addActionListener(this);
        //Create panel and add edit button to panel
        JPanel editPanel = new JPanel();
        editPanel.add(editButton);
        editPanel.setBackground(Color.GRAY);
        soloPanel.add(infoPane, BorderLayout.CENTER);
        soloPanel.add(editPanel, BorderLayout.SOUTH);
        imagePanel.add(soloPanel);
         public static void main(String[] args)
              Display d = new Display();
              d.createAndShowGUI();     
      public void createAndShowGUI()
        //Make sure we have nice window decorations
        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);
        //Create and set up the window
        JFrame frame = new JFrame("IABC");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        contentPanel = new JPanel(new BorderLayout());
        contentPanel.add(buttonPanel, BorderLayout.NORTH);
        contentPanel.add(imagePanel, BorderLayout.SOUTH);
        scrollPane = new JScrollPane(contentPanel);
        frame.setContentPane(scrollPane);
        frame.pack();
        frame.setSize(500, 300);
        frame.setLocation(350, 250);
        frame.setVisible(true);
       frame.setLocationRelativeTo(null);
      public void actionPerformed(ActionEvent event)
       if (ascendButton.isSelected())
           //Sort by natural order
               //Case-insensitive sort, ie. a, C, z
                 if (header.getSelectedIndex() == 0)
            Collections.sort(v, new myComparator());
      else
           //Reverse-order sort
               Collections.sort(v, Collections.reverseOrder());
        list.setListData(v);
        //Reset the model used by the JComboBox after sorting the vector
        DefaultComboBoxModel model = new DefaultComboBoxModel(headerString);
        header.setModel(model);
        System.out.println("After" + v);
        //reconstruct the vector n repaint again
        repaint();
      class myComparator implements Comparator
            public int compare(Object o1, Object o2)
                         String one = (String)o1;
             String two = (String)o2;
             return one.compareTo(two);             
    }

  • Collection sort

    Hi every body I have a small problem in sorting .
    I am taking one collection of type string .When I am sorting I is giving me wrong result.
    Here is my code :
    List <String> caps = new ArrayList<String>();
    caps.add("Alpha");
    caps.add("Beta");
    caps.add("alpha1");
    caps.add("Delta");
    caps.add("theta");
    Collections.sort(caps);It is sorting like :
    Alpha
    Beta
    Delta
    alpha1
    theta.
    Here I can take ant type of string even upper case / lower case .
    But the lower case words are coming later .
    Please help me out.
    thanks ,
    S

    default string sorting is case sensitive. if you want case insensitive sorting, do Collections.sort(caps, String.CASE_INSENSITIVE_ORDER)

  • Re: how to sort an array of type string

    thanks bina and turing pest. well i can't use collections.sort or arrays.sort i need to create a method to sort. stupid instructor dont want to take advantage of this good java language. anyways i am able to do the sort but now OMG the whole data is crappy. formatting is gone everything is fukedd up. excuse my language.
    public void getSort(String[] A)
              String temp= A[0];
                   for(int i=0; i<A.length; i++)
                   for (int j=0; j<A.length-1-i; j++)
                        if(A[j].compareTo(A[j+1])>0)
                             temp = A[j];
                             A[j] = A[j+1];
                             A[j+1] = temp;
         }and here is my output if i dont use the sort before it was not giving me an exception of arraysoutofbound and now it is
    Item          Number      Cost_unit     Sale_unit        TotalSale       profit          Totalprofit
    Binder          500             4       7               3300            1500            1500
    Bookbag         350             5       10              3300            1750            3250
    Calendar        300             3       8               2400            1500            4750
    Shirt           800             4       6               4600            1600            6350
    Notebook        400             1       2               800             400             6750
    Schedule        876             1       2               1752            876             7626and if i turn my sort function on this is what i getg
    Item          Number      Cost_unit     Sale_unit        TotalSale       profit          Totalprofit
    4       500             7       Binder                  3300            1500            1500
    10              350             5       Bookbag                 3300            1750            3250
    3       300             8       Calendar                2400            1500            4750
    4       6       800             Shirt                   4600            1600            6350
    1       2       400             Notebook                800             400             6750
    1       2       876             Schedule                1752            876             7626
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
            at BookStore.main(BookStore.java:62)at this line it is giving me an exception
    totalsale = test.totalSales(Integer.parseInt(str[1].trim()), Integer.parseInt(str[3].trim()));why is it all messed up?

    you create bean for your data like this
    class Person {
       private String name;
       private int age;
       public Person(String name, int age) {
          this.name = name;
          this.age = age;
       public String getName() {
          return name;
       public void setName(String name) {
          this.name = name;
       public int getAge() {
          return age;
       public void setAge(int age) {
          this.age = age;
       public String toString() {
          return "Name : " + name + "\n" + "Age : " + age;
    }after that, just sort it
    public class Sample {
       public static void main(String[] args) {
          Person[] array = new Person[3];
          array[0] = new Person("Dewi", 20);
          array[1] = new Person("Agus", 21);
          array[2] = new Person("Cindy", 18);
          sortByName(array);
          printOut(array);     
       private static void printOut(Person[] array) {
          for(Person person : array){
             System.out.println(person);
             System.out.println();
       private static void sortByName(Person[] array) {
          for (int i = 0; i < array.length; i++) {
             for (int j = array.length - 1; j > i; j--) {
                if (array[j].getName().compareTo(array[j - 1].getName()) < 0) {
                   Person temp = new Person(array[j].getName(), array[j].getAge());
                   array[j].setName(array[j - 1].getName());
                   array[j].setAge(array[j - 1].getAge());
                   array[j - 1].setName(temp.getName());
                   array[j - 1].setAge(temp.getAge());
    }

  • N^2 log(n) for Collections.sort() on a linked list in place?

    So, I was looking over the Java API regarding Collections.sort() on linked lists, and it says it dumps linked lists into an array so that it can call merge sort. Because, otherwise, sorting a linked list in place would lead to a complexity of O(n^2 log n) ... can someone explain how this happens?

    corlettk wrote:
    uj,
    ... there are other sorting methods for linked lists with an O(N*N) complexity.Please, what are those algorithms? I'm guesing they're variants off insertion sort, coz an insertion is O(1) in a linked list [and expensive in array]... Am I warm?You don't have to change the structure of a linked list to sort it. You can use an ordinary Bubblesort. (The list is repeatedly scanned. In each scan adjacent elements are compared and if they're in wrong order they're swapped. When one scan of the list passes without any swaps the list is sorted). This is an O(N*N) algoritm.
    What I mean is it's possible to sort a list with O(N*N) complexity. It doesn't have to be O(N*N*logN) as the Java documentation kind of suggests. In fact I wouldn't be surprised if there were special O(N*logN) algoritms available also for lists but I don't know really. In any case Java uses none of them.

  • Newbie trying to sort 2D string array

    Dear all,
    After read some book chapters, web sites including this, I still don't get the point.
    If I have a file like,
    1 aaa 213 0.9
    3 cbb 514 0.1
    2 abc 219 1.3
    9 bbc 417 10.4
    8 dee 887 2.1
    9 bba 111 7.1
    and I load into memory as a String[][]
    here comes the problem, I sort by column 1 (aaa,...,bba) using an adaptation of the Quicksort algorithm for 2D arrays
    * Sort for a 2D String array
    * @param a an String 2D array
    * @param column column to be sort
    public static void sort(String[][] a, int column) throws Exception {
    QuickSort(a, 0, a.length - 1, column);
    /** Sort elements using QuickSort algorithm
    static void QuickSort(String[][] a, int lo0, int hi0, int column) throws Exception {
    int lo = lo0;
    int hi = hi0;
    int mid;
    String mitad;
    if ( hi0 > lo0) {
    /* Arbitrarily establishing partition element as the midpoint of
    * the array.
    mid = ( lo0 + hi0 ) / 2 ;
    mitad = a[mid][column];
    // loop through the array until indices cross
    while( lo <= hi ) {
    /* find the first element that is greater than or equal to
    * the partition element starting from the left Index.
    while( ( lo < hi0 ) && ( a[lo][column].compareTo(mitad)<0))
    ++lo;
    /* find an element that is smaller than or equal to
    * the partition element starting from the right Index.
    while( ( hi > lo0 ) && ( a[hi][column].compareTo(mitad)>0))
    --hi;
    // if the indexes have not crossed, swap
    if( lo <= hi )
    swap(a, lo, hi);
    ++lo;
    --hi;
    /* If the right index has not reached the left side of array
    * must now sort the left partition.
    if( lo0 < hi )
    QuickSort( a, lo0, hi, column );
    /* If the left index has not reached the right side of array
    * must now sort the right partition.
    if( lo < hi0 )
    QuickSort( a, lo, hi0, column );
    * swap 2D String column
    private static void swap(String[][] array, int k1, int k2){
    String[] temp = array[k1];
    array[k1] = array[k2];
    array[k2] = temp;
    ----- end of the code --------
    if I call this from the main module like this
    import MyUtil.*;
    public class kaka
    public static void main(String[] args) throws Exception
    String[][]a = MyUtil.fileToArray("array.txt");
    MyMatrix.printf(a);
    System.out.println("");
    MyMatrix.sort(a,1);
    MyMatrix.printf(a);
    System.out.println("");
    MyMatrix.sort(a,3);
    MyMatrix.printf(a);
    for the first sorting I get
    1 aaa 213 0.9
    2 abc 219 1.3
    9 bba 111 7.1
    9 bbc 417 10.4
    3 cbb 514 0.1
    8 dee 887 2.1
    (lexicographic)
    but for the second one (column 3) I get
    3 cbb 514 0.1
    1 aaa 213 0.9
    2 abc 219 1.3
    9 bbc 417 10.4
    8 dee 887 2.1
    9 bba 111 7.1
    this is not the order I want to apply to this sorting, I would like to create my own one. but or I can't or I don't know how to use a comparator on this case.
    I don't know if I am rediscovering the wheel with my (Sort String[][], but I think that has be an easy way to sort arrays of arrays better than this one.
    I've been trying to understand the Question of the week 106 (http://developer.java.sun.com/developer/qow/archive/106/) that sounds similar, and perfect for my case. But I don't know how to pass my arrays values to the class Fred().
    Any help will be deeply appreciated
    Thanks for your help and your attention
    Pedro

    public class StringArrayComparator implements Comparator {
      int sortColumn = 0;
      public int setSortColumn(c) { sortColumn = c; }
      public int compareTo(Object o1, Object o2) {
        if (o1 == null && o2 == null)
          return 0;
        if (o1 == null)
          return -1;
        if (o2 == null)
          return 1;
        String[] s1 = (String[])o1;
        String[] s2 = (String[])o2;
        // I assume the elements at position sortColumn is
        // not null nor out of bounds.
        return s1[sortColumn].compareTo(s2[sortColumn]);
    // Then you can use this to sort the 2D array:
    Comparator comparator = new StringArrayComparator();
    comparator.setSortColumn(0); // sort by first column
    String[][] array = ...
    Arrays.sort(array, comparator);I haven't tested the code, so there might be some compiler errors, or an error in the logic.

  • Sort a string :: Please help.

    Hello Everyone,
    I am having this very simple problem of sorting a String. please help.
         static String sortString(String str){
              List list = Arrays.asList(str);                    
              Collections.sort(list);
              for(int i=0, n=list.size();i<n;i++){
                   System.out.println(","+ list.get(i));
    The function is supposed to take a String and sort it & print it out. This should be simple. Where am I making mistakes? Please help!!

    Hello Everyone,
    I am having this very simple problem of sorting a String. please help.
         static String sortString(String str){
              List list = Arrays.asList(str);                    
              Collections.sort(list);
              for(int i=0, n=list.size();i<n;i++){
                   System.out.println(","+ list.get(i));
                   return str;
    The function is supposed to take a String and sort it & print it out. This should be simple. Where am I making mistakes? Please help!!

  • Radix Sort for Type Chars

    I have a code for sorting Radix Sort of type Interger but im not sure how to modify it to sort Characters. This is my code for type Int:
    import java.util.ArrayList;
    import java.util.Iterator;
    public class RadixSort {
        private static final int RADIX = 10;
        private ArrayList[] buckets = new ArrayList[RADIX];
        public RadixSort() {
            for( int i = 0 ; i < RADIX; i++ ) {
                buckets[i] = new ArrayList();
            clearBuckets();
        private void clearBuckets() {
            for( int i = 0 ; i < RADIX; i++ ) {
                buckets.clear();
    private boolean distribute( Integer[] array, int position ) {
    // build the divisor
    int divisor = 1;
    while( position >= 1 ) {
    divisor *= RADIX;
    position--;
    boolean done = true;
    for( int i = 0 ; i < array.length; i++ ) {
    int val = (array[i].intValue()/divisor);
    if ( val != 0 ) done = false;
    int bin = val % RADIX;
    buckets[bin].add( array[ i ] );
    return done;
    private void collect( Integer[] array ) {
    int index = 0; // next available position in array
    for( int i = 0 ; i < RADIX; i++ ) {
    Iterator<Integer> it = buckets[i].iterator();
    while( it.hasNext() ) {
    array[ index ] = it.next();
    it.remove();
    index++;
    // what happens if this removed?
    if ( index >= array.length ) return;
    public void sort( Integer[] array ) {
    clearBuckets(); // is this necessary?
    int position = 0;
    boolean done;
    do {
    done = distribute( array, position );
    position++;
    collect( array );
    } while ( !done );

    As in the maximum size of a string?
    Do you mean characters or actual byte size?

  • How to sort a string as integer

    Hi,
    I need to sort some log files which got timestamps as below:
    1149807013000 this is line no 1
    1149807023000 this is line no 2
    I am converting the date time stamp of the log file to Date.getTime() in a ArrayList and then want to sort this so that i will get them sorted from oldest timestamp to new.
    I am using Collections.sort(ArrayList) method, but it is sorting them as String. As this is simple array would it be possible to tell the sort program to sort as Numeric ?. I donot know how to write comparator for this kind of Array, any help here appreciated.
    Thanks, Mani

    I am posting my method here:
    public static void sortLogs(ArrayList al, JTextArea txa){
            Date t;
            SimpleDateFormat formatter;       
            ArrayList al2=new ArrayList();
            for (int i=0;i < al.size();i++) {
                File file=new File(al.get(i).toString());
                if (file.exists()){
                    if ( file.getName().startsWith("sys_log")){
                        //Jun 26 12:40:51 2006 BoxMonitor:3:526 enclosure 2 failed to respond to ping at management switch
                        //MMMsDDsTIMEsYR_data
                        try{
                            BufferedReader in=new BufferedReader(new FileReader(file));
                            String line=null;
                            formatter=new SimpleDateFormat("MMM dd HH:mm:ss yyyy",new Locale("en", "US"));
                            while ( (line=in.readLine())!=null){
                                Pattern p=Pattern.compile("^([JFMASOND][aepuco][nbrylgptvc])\\s+([\\d]+)\\s+([\\d]+[:][\\d]+[:][\\d]+)\\s+([\\d]+)\\s+(.*)");// \\s+(.*)");
                                Matcher m=p.matcher(line);
                                if (m.find()){
                                    t=formatter.parse(m.group(1)+" "+m.group(2)+" "+m.group(3)+" "+m.group(4));
                                    al2.add(t.getTime() + " "+file.getName()+" " + m.group(5));                               
                        }catch(Exception ex){
                            System.err.println("Error on file "+file.getPath()+ " error is "+ ex.getMessage());
            if ( al2.size() > 0) {
                t=new Date();
                formatter=new SimpleDateFormat("MMM dd HH:mm:ss yyyy",new Locale("en", "US"));
                Collections.sort(al2);    //once arraylist al2 is populated with all the files, want to sort which contains String lines like 102020000 filename data
                Pattern p=Pattern.compile("^(\\d+)\\s+(.*)");
                Matcher m;
                for (int j=0;j< al2.size();j++){
                    m=p.matcher(al2.get(j).toString());                          
                    if ( m.find()) {
                       t.setTime(Long.parseLong(m.group(1)));
                       txa.append(formatter.format(t)+" "+m.group(2)+"\n");                               
        }I am using Collections.sort. As you can see here i am perl guy trying to port my script to java. Was using unix sort on my perl script, but here i am stuck :-).
    The ArrayList populated here from reading the text files - finding the date pattern - converting to ephoch seconds, and then i need to sort before converting back to normal date. When i verified the sort output, i see sorting like below:
    1
    100
    2
    20
    where as in numeric i would like to see,
    1
    2
    20
    100
    Thanks for your help.

  • OrderedList sorted by String length

    i am trying to create an orderedlist of strings in ascending order by length. I am a little shacky on comparables this is what i have so far. I think i have to implement the Comparable interface and use length as the comparison in the Word class but im not entirely sure how to do this. So for example lion, pig, crocodile should look like ....
    pig
    lion
    crocodile
    in the ordered list... any help is appreciated.
    WORD.JAVA
    public class Word
         private String word, description;
         private int startPos, direction, used;
         public static final int NOTUSED = 0;
         public static final int USED = 1;
         public static final int DOWN= 0;
         public static final int ACROSS= 1;
         public Word(String w, String d)
              word = w;
              description = d;
              //startPos = num;
              //direction = dir;
              //used = use;
         public void setDirection(int dir)
              direction = dir;
         public int getDirection()
              return direction;
         public void setUsed(int use)
              used = use;
         public int getUsed()
              return used;
         public void setPos(int num)
              startPos = num;
         public int getPos()
              return startPos;
         public String getDescription()
              return description;
         public String getWord()
              return word;
         public String toString()
              String str = "";
              str = word+": "+description;
              return str;
    ORDEREDLIST.JAVA
    import java.util.*;
    public class OrderedLinkedList
         private class LinearNode
              private LinearNode next = null;
              private Comparable element = null;
              public LinearNode(Comparable c)
                   element = c;
              public LinearNode getNext()
                   return next;
              public void setNext(LinearNode n)
                   next = n;
              public Comparable getElement()
                   return element;
              public void setElement(Comparable c)
                   element = c;
              public String toStringRecursive()
                   String result = element.toString();
                   if(next == null)
                        return null;
                   else
                        return result + " " + next.toStringRecursive();
              public void add(LinearNode node)
                   if(node.element.compareTo(next.element) <= 0)
                        node.next = next;
                        next = node;
                   else
                        next.add(node);
         private LinearNode first = null;
         private LinearNode last = null;
         private int count = 0;
         public void add(Comparable c)
              LinearNode node = new LinearNode(c);
              if(isEmpty())
                   first = node;
                   last = node;
              else if(count == 1)//(first == last)
                   if(c.compareTo(first.getElement()) > 0) //one in list add to end
                        last = node;
                        first.setNext(last);
                   }else                                   //one in list add to start
                        first = node;
                   first.setNext(last);
              else if(c.compareTo(first.getElement()) <= 0) //multiple in list add to start
                   node.setNext(first);
                   first = node;
              }else if(c.compareTo(last.getElement()) > 0) //multiple in list add to end
                   last.setNext(node);
                   last = node;
              }else
                   first.add(node);
              count++;
         public Comparable remove(Comparable target) throws EmptyStackException,NoSuchElementException
              if(isEmpty())
                   throw new EmptyStackException();
              boolean found = false;
              LinearNode previous = null;
              LinearNode current = first;
              while(current != null && !found)
                   if(target.equals(current.getElement()))
                             found = true;
                   else{
                        previous = current;
                        current = current.getNext();
              if(!found)
                   throw new NoSuchElementException();
              if(size() == 1)
                   first = last = null;
              else if (current.equals(first))
                   first = current.getNext();
                   else if(current.equals(last))
                             last = previous;
                             last.setNext(null);
                        else
                             previous.setNext(current.getNext());
              count--;
              return current.getElement();
         public boolean isEmpty()
              return count == 0;
              //return first == null;
         public String toString()
              String result = "";
              LinearNode current = first;
              while(current != null)
                   result += current.getElement();
                   current = current.getNext();
              return result;
         public int size()
              return count;
    }

    That's rather a lot of code - and much of it has nothing obvious to do with sorting strings by length. Also I can't see where you have implemented the Comparable interface.
    You are talking about java.lang.Comparable, right? In that case some class (Word?) has to be declared as "implements Comparable".
    Another way to do this is is to have an instance of Comparator that you use when you create an ordered collection like a TreeSet.
    Have you read the JavaWorld article: [http://www.javaworld.com/javaworld/jw-12-2002/jw-1227-sort.html]. It is rather old now and doesn't make any use of generics. But it gives examples of a simple collection - a list - being sorted using Collections.sort(). Both the Comparable and Comparator approaches are illustrated

  • Problem in sorting numeric string

    hii
    i have created one method using comparator and passed a list with list of strings as argument to sort method of Collections class.The string ,which is combined a string and numeric value for example A1,A2,A11,A3 .....So i wanted the result as A1,A2,A3..A11,A12... and so on as final output.but when i print the output ,they are sorted as A1,A11,A12....A2,A3....so i learned from javadoc why those are sorted as like since comparator is using charAt() method while making override compare() method.but i am not expected this sorting for my application. i need sorting output as A1,A2,A3...A11,A12.....How to compare a string with another string both have combination of string and number using java?
    if any one know the logic reply me.
    i have pasted my code,if any changes have to be made only in this code,correct the code.
    package sample.sorting;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    public class SortString {
         public static List<String> sort(List<String> data) {
              Collections.sort(data,new Comparator<String>(){
                   public int compare(String s1,String s2) {
                        return s1.compareTo(s2)     ;
              return data;
         public static void main(String[] args) {
              List<String> sortList     = new ArrayList<String>();
              sortList.add("A1");
              sortList.add("A3");
              sortList.add("A2");
              sortList.add("A9");
              sortList.add("A11");
              sortList.add("A6");
              List<String> sort = sort(sortList);
              for(String str : sort) {
                   System.out.println("STR :: "+str); // O/P : A1,A11,A2,A3,A6... but expected O/P : A1,A2,A3..A11.
    }thanks in advance.
    with regards
    Oasisderts
    Edited by: oasisdesert on Dec 29, 2009 4:15 AM

    In the compare method of the comparator, check if two Strings have equal length, if so compare them as normal, otherwise treat them as a separate case.
    e.g. uncompiled return s1.length == s2.length ? s1.compareTo(s2) : if(s1.length < s2.length) -1 else 1;Mel

  • Compiler warning with Collections.sort() method

    Hi,
    I am sorting a Vector that contains CardTiles objects. CardTiles is a class that extends JButton and implements Comparable. The code works fine but i get the following warning after compilation.
    Note: DeckOfCards.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    After compiling with -Xlint, i get the following warning;
    DeckOfCards.java:173: warning: [unchecked] unchecked method invocation: <T>sort(java.util.List<T>) in java.util.Collections is applied to (java.util.Vector<CardTiles>)
    Collections.sort(handTwo);
    ^
    What could be the problem? Is Collections.sort() only intended for Collections of type List?
    Many thanks!

    Hi Jverd, my handTwo Vector was declared as follows;
    Vector<CardTiles> handTwo = new Vector<CardTiles>();
    The CardTiles Source code is as follows;
    import javax.swing.*;
    import java.util.*;
    public class CardTiles extends JButton implements Comparable{
         static String typeOfSort = "face";
         public static final long serialVersionUID = 24362462L;
         int i=1;
         public ImageIcon myIcon;
         public Card myCard;
         public CardTiles(ImageIcon i, Card c){
              super(i);
              myIcon = i;
              myCard = c;
         public int compareTo(Object o){
              CardTiles compare = (CardTiles)o;
              if(typeOfSort.equals("face")){
                   Integer ref1 = new Integer(this.myCard.getFaceValue());
                   Integer ref2 = new Integer(compare.myCard.getFaceValue());
                   return ref1.compareTo(ref2);
              }else{
                   if(this.myCard.getFaceValue() > 9 || compare.myCard.getFaceValue() >9){
                        if(this.myCard.getFaceValue() > 9 && compare.myCard.getFaceValue() >9){
                             String ref1 = this.myCard.getSuit().substring(0,(this.myCard.getSuit().length()-1));
                             String ref2 = compare.myCard.getSuit().substring(0,(compare.myCard.getSuit().length()-1));
                             return ref1.compareTo(ref2);
                        }else{
                             if(this.myCard.getFaceValue() > 9 || compare.myCard.getFaceValue() >9){
                                  String ref1 = this.myCard.getSuit().substring(0,(this.myCard.getSuit().length()-1));
                                  String ref2 = compare.myCard.getSuit() + Integer.toString(compare.myCard.getFaceValue());
                                  return ref1.compareTo(ref2);
                             }else{
                                  String ref1 = this.myCard.getSuit() + Integer.toString(this.myCard.getFaceValue());
                                  String ref2 = compare.myCard.getSuit().substring(0,(compare.myCard.getSuit().length()-1));
                                  return ref1.compareTo(ref2);
                   }else{
                        String ref1 = this.myCard.getSuit() + Integer.toString(this.myCard.getFaceValue());
                        String ref2 = compare.myCard.getSuit() + Integer.toString(compare.myCard.getFaceValue());
                        return ref1.compareTo(ref2);
         public String toString(){
              return ( myCard.toString() + " with fileName " + myIcon.toString());
    }What could be wrong?
    Many thanks!

Maybe you are looking for