java:树集顺序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23365307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:15:58  来源:igfitidea点击:

java: TreeSet order

javatreeset

提问by Enzo

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 

采纳答案by jgitter

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.

TreeSet 实现按您插入的字符串值的字典顺序进行排序。如果您想按整数值排序,那么您需要按照其他人的建议进行操作并创建一个新对象并覆盖 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>();

回答by ethanfar

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

回答by Tim B

You can use one of the TreeSetconstructors: 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 Comparatorthat extracts the number from the Stringand then sorts by the number first, only falling back to a Stringcomparison if both numbers are equal.

实现 aComparator从 中提取数字String,然后首先按数字排序,只有String在两个数字相等时才回退到比较。

回答by Grim

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

回答by Afsar_Abbas

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

回答by Vivek

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.

  1. 这是一个与查找数组中第二大元素相关的程序。我使用 Tree-set 进行排序。使用树集,我们可以删除所有重复的元素。

  2. 使用 set 方法对元素进行排序后。有一个函数 set.last() ,您可以通过它找到数组或列表的最后一个元素。

  3. 我应用了 set.last()-1 函数,该函数为我提供了数组中的第二大元素。

回答by jalbertomr

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.

但我强烈建议在其他关键结构中分离重要值(在本例中为整数)。以便于操作。