简体   繁体   English

java:树集顺序

[英]java: TreeSet order

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?如何使用 TreeSet 根据数字获得此类订单?

  dfd 2 
  asdt 10 
  test 15
  ersfd 20 

The TreeSet implementation is sorting by the lexicographic order of the string values you insert. TreeSet 实现按您插入的字符串值的字典顺序进行排序。 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.如果您想按整数值排序,那么您需要按照其他人的建议进行操作并创建一个新对象并覆盖 compareTo 方法,或者使用您自己的比较器。

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

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您可以使用TreeSet构造函数之一: 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.这允许您指定自己的比较器,以便您可以随意组织 Set 中的条目。

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.实现一个Comparator ,从String中提取数字,然后首先按数字排序,只有在两个数字相等时才回退到String比较。

Use the TreeSet constructor that receives a custom Comparator, and implement a Comparator that sorts the string differently.使用接收自定义 Comparator 的 TreeSet 构造函数,并实现一个以不同方式对字符串进行排序的 Comparator。

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使用 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.我使用 Tree-set 进行排序。 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.使用 set 方法对元素进行排序后。有一个函数 set.last() ,您可以通过它找到数组或列表的最后一个元素。

  3. I applied set.last()-1 function that gives me second largest element in array.我应用了 set.last()-1 函数,它为我提供了数组中的第二大元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM