Question

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 
Was it helpful?

Solution

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

OTHER TIPS

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.

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

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.

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;
   }
});
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);  
       }  
   }  
}  
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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top