11

With this code I get this output:

 TreeSet<String> t=new TreeSet<String>();
  t.add("test 15");
  t.add("dfd 2");
  t.add("ersfd 20");
  t.add("asdt 10");


 Iterator<String> it=t.iterator();

 while(it.hasNext()){
   System.out.println(it.next);
 }

I get:

  asdt 10 
  dfd 2 
  ersfd 20 
  test 15

How can I get an order of this kind, based on the numbers, with TreeSet?

  dfd 2 
  asdt 10 
  test 15
  ersfd 20 
Enzo
  • 597
  • 1
  • 8
  • 22
  • 7
    use a comparator. – njzk2 Apr 29 '14 at 12:57
  • 3
    Instead of having values like "dfd 2" in one string. It would be better if you have it in 2 separate fields in a java object (eg YourObject). TreeSet t=new TreeSet(); – Jay Apr 29 '14 at 13:11

7 Answers7

18

The TreeSet implementation is sorting by the lexicographic order of the string values you insert. If you want to sort by the integer value, then you'll need to do as these others suggested and create a new object and override the compareTo method, or use your own comparator.

Set<String> set = new TreeSet<String>(new Comparator<String>() {

    public int compare(String one, String other) {
        // implement
    }

});

or

public class MyClass implements Comparable {
    private String key;
    private int value;

    public int compareTo(MyClass other) {
        // implement
    }

    public boolean equals(MyClass other) {
        // implement
    }

    // snip ...
}

Set<MyClass> set = new TreeSet<MyClass>();
Ala Abid
  • 2,256
  • 23
  • 35
jgitter
  • 3,396
  • 1
  • 19
  • 26
2

You can use one of the TreeSet constructors: http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html#TreeSet%28java.util.Comparator%29

This allows you to specify your own comparator that allows you to organize the entries in the Set however you like.

Implement a Comparator that extracts the number from the String and then sorts by the number first, only falling back to a String comparison if both numbers are equal.

Tim B
  • 40,716
  • 16
  • 83
  • 128
1

Use the TreeSet constructor that receives a custom Comparator, and implement a Comparator that sorts the string differently.

Here's an example (untested, check the code before using):

TreeSet<String> t = new TreeSet<String>(new Comparator<String>() {
    public int compare(String s1, String s2) {
        int spaceIndex1 = s1.indexOf(' ');
        int spaceIndex2 = s2.indexOf(' ');

        return Integer.parseInt(s1.substring(spaceIndex1 + 1)).compareTo(Integer.parseInt(s2.spaceIndex2 + 1));
    }
});
ethanfar
  • 3,733
  • 24
  • 43
  • 1
    That's still doing a `String` comparison so "20" will come before "4". He needs to extract the number and do a numerical comparison. – Tim B Apr 29 '14 at 13:07
  • Yep, that will work. Although I'd class it as "fragile" code in that if the format of the strings changes even slightly it could cause NumberFormatExceptions to start being thrown. That may be fine in this case but it depends on how constrained the input data is. – Tim B Apr 29 '14 at 13:15
1

Using lambda

Set<String> set = new TreeSet<String>(
                (o1, o2) -> String.format("%3s", o1.substring( o1.indexOf(" ") + 1)).replace(" ","0")
                .compareTo( String.format("%3s", o2.substring( o2.indexOf(" ") + 1)).replace(" ","0")
                                     ));
set.add("test 15");
set.add("dfd 2");
set.add("ersfd 20");
set.add("asdt 10");
set.stream().forEach(s -> System.out.println(s));

result:

dfd 2
asdt 10
test 15
ersfd 20

But I strongly recommend separe the significant values (in this case integers) in other key estucture. for easy manipulation.

jalbertomr
  • 31
  • 2
0

Try this:

TreeSet set = new TreeSet(new Comparator<String>(){
   public int compare(String o1, String o2){
         String n1 = o1.split(" ")[1];
         String n2 = o2.split(" ")[1];
         return Integer.parse(n2) - Integer.parse(n1);
   }
   public boolean equals(String o1, String o2){
        return compare(o1,o2)==0;
   }
});
Grim
  • 1,938
  • 10
  • 56
  • 123
  • 1
    That isn't valid java. Also, I would add some error-checking. – jgitter Apr 29 '14 at 13:12
  • 1
    This code doesn't compile/work. There's no method `parse()` for class `Integer`, and the `>` operator returns `boolean`, not `int`. – ethanfar Apr 29 '14 at 13:14
  • I would throw a exception like ArrayIndexOutOfBoundsException ... hey the code already throw it. ;D – Grim Apr 29 '14 at 13:14
0
class Book implements Comparable<Book> {    
   String name;  
   int id;

   public Book(String name,int id) {  
       this.name = name;  
       this.id = id;   
   }  

   public int compareTo(Book b) {  
       if(id>b.id){  
           return 1;  
       }else if(id<b.id){  
           return -1;  
       }else{  
          return 0;  
       }  
   }  
}

public class TreeSet2 {  
   public static void main(String[] args) {  
       Set<Book> set=new TreeSet<Book>();  

       //Creating Books  
       Book b1=new Book("test", 15);  
       Book b2=new Book("dfd", 2);  
       Book b3=new Book("ersfd", 20);
       Book b4=new Book("asdt", 10);  

       //Adding Books to TreeSet  
       set.add(b1);  
       set.add(b2);  
       set.add(b3);
       set.add(b4);  

       //Traversing TreeSet  
       for(Book b:set){  
          System.out.println(b.name+" "+b.id);  
       }  
   }  
}  
Jameson
  • 6,400
  • 6
  • 32
  • 53
0
import java.util.ArrayList;
import java.util.*;
import java.util.Arrays;
class SecondHighest {
    public static void main(String[] args) {
        int i;
        int a[]={2,3,4,5,7,6,9,9,9,8,8,7};
        int total=a.length;

        Arrays.sort(a);

        TreeSet<Integer> set=new TreeSet<Integer>();
        for(i=0;i<total;i++)
        {
            set.add(a[i]);
        }
        System.out.println(set.last()-1);

        Iterator<Integer> itr=set.iterator();
        while(itr.hasNext())
        {
            System.out.println(itr.next());
        }
    }

}
  1. This is a program related to find the second largest element in array. I have used Tree-set for sorting purpose. Using tree-set we can remove all the repeated elements.

  2. After sorting element using set method.There is a function set.last() by which you can find the last element of array or list.

  3. I applied set.last()-1 function that gives me second largest element in array.

RalfFriedl
  • 1,134
  • 3
  • 11
  • 12
Vivek
  • 1
  • 1
  • 4