jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes Sorting String List Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Sorting String List" Watch "Sorting String List" New topic
Author

Sorting String List

Venkata Sirish
Ranch Hand

Joined: Apr 09, 2007
Posts: 112
Hi all,

I want to sort the string list in the following order.

game1, game2, game3, game10, game20, game110.


I have tried with the below code, but it did not work. Can any one help me.

TreeSet ts = new TreeSet();

ts.add("game1");
ts.add("game10");
ts.add("game110");
ts.add("game3");
ts.add("game2");
ts.add("game20");



Iterator it = ts.iterator();
while (it.hasNext()) {
Object element = it.next();

System.out.println(element);
}


Thanks,
Venkat
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

I have tried with the below code, but it did not work. Can any one help me.


By default, string objects are sorted in natural order -- meaning ascii order. If you want a different order, you will have to write a comparator, and pass it in the constructor of the TreeSet.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Venkata Sirish
Ranch Hand

Joined: Apr 09, 2007
Posts: 112
Hi,
I found it.

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetTest {

public static void main(String[] args) {

TreeSet ts = new TreeSet(new Comparator() {

public int compare(Object o1, Object o2) {

Emp e1 = (Emp) o1;
Emp e2 = (Emp) o2;

int int1 = e1.getName().compareTo(e2.getName());

int int2 = new Integer(e1.getAge()).compareTo(new Integer(e2.getAge()));

if (int1 == 0) {
return int2;

} else
return int1;
}

});

ts.add(new Emp("game", 1));
ts.add(new Emp("game", 10));
ts.add(new Emp("game", 110));
ts.add(new Emp("game", 2));
ts.add(new Emp("game", 30));


Iterator it = ts.iterator();
while (it.hasNext()) {
// Get element
Emp element = (Emp) it.next();

System.out.println(element.getName() + "\t" + element.getAge());
}

}

}

/////////////


package collectionss;

public class Emp {

private String name;
private int age;

Emp(String name, int age){
this.name=name;
this.age=age;
}
/**
* @return Returns the age.
*/
public int getAge() {
return age;
}
/**
* @param age The age to set.
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return Returns the name.
*/
public String getName() {
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name) {
this.name = name;
}

}


Thanks,
Venkat
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Sorting String List